Top Banner
Microcontroller Interfacing - Introduction http://www.w9xt.com/page_microdesign_pt1_intro.html[27/06/2011 1:33:34 PM] Home Electronics Tropical Fish Garden Ham Radio Microcontroller Interfacing – Part 1 Introduction Developing embedded systems that interface microcontrollers to the outside world is a fascinating endeavor. Such systems require both hardware and software development. Most of the literature covers the programming of the microcontrollers. There does not seen to be as much that describes the practical aspects of designing the circuits that interact with the outside world. The purpose of this series is to introduce the reader in how to design simple microcontroller interface circuits in embedded systems. It is assumed the reader has a basic understanding of electronics. The emphasis will be how to use this basic knowledge to create functional and reliable circuits. A special effort will be made to point out which things must be carefully considered, and the areas where precision is not necessary. Rather than just provide a compendium of common microcontroller interface circuits, this series will attempt to go through the steps of the actual design process, trade offs, and other considerations. If a circuit described here does not quite meet the requirements of their application, the reader will hopefully be in a position to make the design changes themselves. Circuit design requires a certain amount of mathematics for calculating component values. When math is required, it will be kept as simple as possible. The basic equation used will be shown, followed by the equation with the example values substituted for the variables, and the final answer. The reader can then follow the process presented, and make adjustments to suit their own application’s requirements. When actual microcontroller specifications are used as examples, Microchip PIC and Atmel AVR units will be referenced. These are both very popular microcontroller families. They have low cost development tools available and the components themselves are low cost. In some cases, some of the smaller components can be purchased in single quantities for well under a dollar. Larger and more powerful microcontrollers can be purchased for a few dollars. That is a lot of computing power for very little money. Although the main point of this series is on hardware, sometimes it will be necessary to discuss programming. It will be kept to a minimum and attempts will be made to keep program examples generic. The series will start with the basics and move to more complex subjects. Additional parts will be added as time allows. Most of this series will cover low voltage circuits. Extreme caution must be exercised when working with high voltage circuits. Every effort is made to ensure this information is correct. This information is provided as is, and without warranty. The reader is responsible for implementing any circuits in a safe manner. Development hardware and software for many microcontrollers is powerful and inexpensive. The immensely popular Arduino systems are a great way to start. The open source software handles a lot of the low level details, allowing new programmers to get their applications running quickly. Arduino hardware is low cost and available from a number of vendors. Sidebars with Circuit oscilloscope 8 Out of 10 Engineers Rely on Our Oscilloscopes. Come See Why Today. www.tek.com Real Time Embedded System Leaders in Embedded Subsystems For ISR Applications. Learn More. www.mc.com Smarter Document Tracking Scan paper into text-
52

Micro Controller Interfacing

Nov 28, 2014

Download

Documents

12345ace12345
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Micro Controller Interfacing

Microcontroller Interfacing - Introduction

httpwwww9xtcompage_microdesign_pt1_introhtml[27062011 13334 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 1Introduction

Developing embedded systems that interface microcontrollers to the outside world is a fascinating endeavor Suchsystems require both hardware and software development Most of the literature covers the programming of themicrocontrollers There does not seen to be as much that describes the practical aspects of designing the circuitsthat interact with the outside world

The purpose of this series is to introduce the reader in how to design simple microcontroller interface circuits inembedded systems It is assumed the reader has a basic understanding of electronics The emphasis will be how touse this basic knowledge to create functional and reliable circuits A special effort will be made to point out whichthings must be carefully considered and the areas where precision is not necessary

Rather than just provide a compendium of common microcontroller interface circuits this series will attempt to gothrough the steps of the actual design process trade offs and other considerations If a circuit described here doesnot quite meet the requirements of their application the reader will hopefully be in a position to make the designchanges themselves

Circuit design requires a certain amount of mathematics for calculatingcomponent values When math is required it will be kept as simple aspossible The basic equation used will be shown followed by the equationwith the example values substituted for the variables and the final answer The reader can then follow the process presented and make adjustments tosuit their own applicationrsquos requirements

When actual microcontroller specifications are used as examples MicrochipPIC and Atmel AVR units will be referenced These are both very popularmicrocontroller families They have low cost development tools availableand the components themselves are low cost In some cases some of thesmaller components can be purchased in single quantities for well under adollar Larger and more powerful microcontrollers can be purchased for afew dollars That is a lot of computing power for very little money

Although the main point of this series is on hardware sometimes it will benecessary to discuss programming It will be kept to a minimum andattempts will be made to keep program examples generic

The series will start with the basics and move to more complex subjects Additional parts will be added as time allows

Most of this series will cover low voltage circuits Extreme caution must beexercised when working with high voltage circuits Every effort is made toensure this information is correct This information is provided as is andwithout warranty The reader is responsible for implementing any circuits ina safe manner

Development hardware and software for many microcontrollers is powerfuland inexpensive The immensely popular Arduino systems are a great wayto start The open source software handles a lot of the low level detailsallowing new programmers to get their applications running quickly Arduinohardware is low cost and available from a number of vendors Sidebars with

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Real TimeEmbedded SystemLeaders in EmbeddedSubsystems For ISRApplications LearnMorewwwmccom

Smarter DocumentTrackingScan paper into text-

Microcontroller Interfacing - Introduction

httpwwww9xtcompage_microdesign_pt1_introhtml[27062011 13334 PM]

Created with the QTHcom SiteBuilder

special tips for Arduino users are included on some topic pages

Note that the series may not follow a logical order Sections are added as Iget the urge or based on requests from readers Rather than re-sortingthem from time to time I decided to leave them in the order they are writtenso that external links to these pages are not affected

Im always looking for feedback on this series Please contact me if you findany errors If there is a specific topic you would like covered please sendme an email and I will put it on the list for consideration for futureinstallments Email w9xt (at) unifiedmicro (dot) com Be sure to includeldquoMicrocontroller IF Seriesrdquo in the subject line so it will not be caught in thespam filter

Enjoy your journey into the world of embedded systems

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 2

Back to Electronics Main PageHome Page

Unified Microsystems Electronic equipmentmodules and kits for engineers studentselectronic hobbyists and Amateur Radiooperators

copy 2009 - 2011 Gary C Sutcliffe

searchable PDF Senddocument directly intoDMSECMwwwomtoolcomAccuRoute

Habey USA BIS-6622Ultra-Conpact FanlessPCs Tunnel CreekIntel Atom E6xx serieswwwhabeyusacom

ApplicationsIntegrationGo Open Source ForYour ApplicationIntegration FreeProduct DownloadwwwtalendcomFree_Intehellip

Microcontroller Interfacing - Basic Electronics

httpwwww9xtcompage_microdesign_pt2_basic_electhtml[27062011 13404 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 2Basic Electricity Review

GoalThis section covers some basics of electricity It is assumed that the reader has a basic knowledge of electronics andthis is a quick review

Ohmrsquos Law

Figure 2-1 shows the simplest circuit possible It consists of a voltage source and a single resistor The voltagesource is DC in this case Unless otherwise noted we will be dealing exclusively with DC voltage in this series Inmicrocontroller circuits the power source will usually be a power supply or battery In most cases the voltages wewill be working with will be 12 volts or less

With a given voltage (V) and resistor value (R) a given current (I) will flow A simple equation Ohmrsquos Law gives therelationship between voltage resistance and current

V = I RSimple algebra lets us manipulate the equation to solve for the unknown variable

I = VR or R = VI

In Figure 2-1 if we know our voltage source is 5V and we have a 1000 ohmresistor we can calculate the current in amperes

I = VR = 51000 = 005 A more often stated as 5 ma

In designing circuits we often have a given value for one parameter of V R orI and a desired value for one of the other variables The goal is to select theremaining component to give provide the desired value For example supposewe have a 12 V battery and want 65 ma of current What resistor value do weneed

R = VI = 12065 = 1846 ohms

Now finding a 1846 ohm resistor is going to be difficult but fortunately in mostcases you do not need (and are unable) to get that sort of precision Theclosest standard 5 resistor is 180 ohms If we use a 180 ohm resistor and itis right on 180 ohms (it wonrsquot be) we will get the following current

I = VR = 12180 = 067 A or 67 ma In most cases this will be close enough Figure 2-1

Voltage DividersFigure 2-2 shows a slightly more complex circuit one that has a voltagesource and two resistors There are several points to illustrate with sucha circuit The first is that resistors in series have a total resistance equalto the sum of the individual resistances

Microcontroller Interfacing - Basic Electronics

httpwwww9xtcompage_microdesign_pt2_basic_electhtml[27062011 13404 PM]

What would the current be in the circuit shown in Figure 2-2 be Sincethe two resistors could be substituted by a single resistor with a valueequal to the sum of the two Ohmrsquos Law states

I = V(R1 + R2)The other important point is to realize the there will be a voltage acrosseach component in the circuit If you put a voltmeter across the powersource you would read Vs Measuring across R1 you would measurevoltage V1 Voltage V2 would appear across R2

Note the polarity of the voltages with reference to the arrow indicatingcurrent The ones across the resistors are opposite polarity of thevoltage source This is because the net voltage around the loop must bezero Mathematically the voltages follow this equation

Vs = V1 + V2So what are the voltages V1 and V2 That depends on the ratio of thevalues of R1 and R2 The voltage across a resistor will be proportional tothe value of that resistor compared to the total The following equationsapply

V1 = Vs R1(R1+R2) V2 = Vs R2(R1+ R2)If we had three resistors in the circuit the following would apply

V1 = Vs R1(R1+R2+R3)

Suppose Vs = 12V R1 = 1200Ω and R2 = 2400Ω What is the voltageacross each resistor

V1 = Vs R1(R1+R2) = 12 1200(1200 +2400) = 4 V

To calculate the voltage across R2 we could use the equation for V2 orwe could apply the knowledge that the total voltage across the loop mustequal 0V

Vs = V1 + V2 --gt V2 = Vs - V1 = 12- 4 = 8V

SummaryDesigning interface circuits to microcontrollers requires some simplemathematics Understanding Ohmrsquos Law and voltage dividers will covera large percentage of the situations for simple circuits

Figure 2-2

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Flexible PrintedCircuitsFlexible Printed CircuitBoards Quick Turn ampFlex Circuit Assemblywwwallflexinccom

Electric circuitsanswersElectric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

PCB - IntroductoryOffer2 Layers $25ea - 4Layers $50ea Even 1piece is Ok - NoToolingwwwPCBnetcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relay

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 1Microcontroller Interfacing Part 3

Microcontroller Interfacing - Basic Electronics

httpwwww9xtcompage_microdesign_pt2_basic_electhtml[27062011 13404 PM]

Created with the QTHcom SiteBuilder

Back to Electronics Main PageHome Page

assembliesanaconpowercom

copy 2009 - 2011 Gary C Sutcliffe

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

Electric circuits 9Electric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Real TimeEmbedded SystemLeaders in EmbeddedSubsystems For ISRApplications LearnMorewwwmccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Electric circuits 9Electric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

Analyze EmbeddedCodeFind and fix criticalbugs with CodeSonarFree evaluationwwwGrammaTechcom

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 3Microcontroller Digital Output Basics

GoalThis section goes over the basics of microcontroller output ports It will cover how they can be used to interface to theoutside world and some of the limitations A separate section will cover use of microcontroller IO pins as inputs

Digital IO PortsMicrocontrollers generally combine their output pins into 8 bit ports Op code instructions allow easy manipulations ofthe values as a byte Byte operations are convenient when all 8 bits are part of a data byte At other times you willwant use each bit for a different specific purpose You might want one bit to control an LED a couple more to controlrelays etc There will be op code instructions that let you manipulate individual bits If you program in C Basic orother high level language the compiler will have instructions for controlling individual bits

Most IO pins on a microcontroller can be set as digital inputs or outputs You will want to configure them in the desireddirection early in the software that is executed when the microcontroller is powered up or reset There will be specialregisters for this purpose

The individual pins of an output port can have one of twooutput voltages depending on how the bit is set in the portrsquosoutput register If the bit is set to a ldquo1rdquo the output pin willhave a high voltage The value of the voltage will usuallybe the same as the microcontrollerrsquos supply voltageSometimes setting a bit to a 1 is also called setting it highor just setting the bit Depending on the system design thiswill usually be 33V or 5V Some new microcontrollerdesigned for low power battery applications run at lowervoltages

If the output pin is set to a ldquo0rdquo the voltage at the pin will beclose to zero volts This is also called clearing the bit orsetting it low

The different voltages are obtained by internal transistorsthat switch the output pin to the supply voltage or groundFigure 3-1 is a simplified diagram of an output pinarbitrarily labeled P0 for this example

The red transistor will be on when the output is set to alogical lsquo1rsquo Output pin P0 will be connected to +5V in thisexample If the output is set to a logical lsquo0rsquo the bluetransistor will be on connecting the output pin to ground or0V Only one of the two transistors can be on at a time Both transistors will be off if the pin is configured as aninput and in some other special conditions but one of thetwo will be on if the pin is configured as an output

Driving LoadsAn output pin not connected to anything is not of much

Figure 3-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

interest To do something useful it must be connected toanother device referred here simply as a ldquoloadrdquo A realworld load could be an LED a lamp a transistor or someother circuit element

Generally there are two ways to connect an output pin to aload The first is where the microcontroller supplies thecurrent to drive the device The microcontroller is referredto as the source Current flows from the microcontrollerpower to the output pin through the load and to groundThis configuration is shown in Figure 3-2a

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

The microcontroller pin can also ldquosinkrdquo the current asshown in Figure 3-2b Here the current flows fromthe power supply through the load and through theoutput pin to ground It is important that the load beconnected to the same power supply line as themicrocontroller or you can destroy the IC

Output CurrentsMicrocontrollers are somewhat delicate devices andthe IO lines can only carry a relatively small amountof current The current limit will depend on the typeof microcontroller and the specific pin There willusually be a maximum total current the pins of asingle 8 bit port can handle as well as a limit for allof the outputs for the entire microcontrollerExceeding the limits will destroy the microcontroller

To find out what the maximum currents are youneed to look at the data sheet for the microcontrollerPDF formatted data sheets can be downloaded fromthe manufacturer These can be quite large several

Figure 3-2

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Buy Electronic LED Sign wwwMegaSignInccom

Spend Less On Top Quality Long LastingProgrammable LED Order Now

Pro Energy wwwproenergyca

Rental Power Solutions Generators LightsElectrical Dist

Solid State Relays anaconpowercom

Manufacturer of DIN and Panel mount solid staterelay assemblies

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

hundred pages for a fairly complex one Look for asection titled ldquoElectrical Specificationsrdquo or somethingsimilar Usually in the section there will be a tablecalled ldquoAbsolute Maximum Ratingsrdquo or similar Youwill find a table containing a number of specificationsincluding

Characteristic Symbol ValueOutput Source Current

Ioh -25ma

Output Sink Current Iol 25ma

Ioh stands for Current (I) output high Iol stands for current output low Currents are traditionally referenced as goinginto a pin If the output is high the current flows out so it is given a negative number In some microcontrollers themaximum sink and source current limits for a given pin might be different You will also want to check the portion ofthe data sheet that covers the port you are using Some ports have more drive capacity than others on somemicrocontrollers Exceptions will be spelled out there

Some manufacturers such as Atmel will not give a single value for the maximum current allowed for output pinsInstead they provide a graph that plots the Voh vs Ioh and Vol vs Iol Voh stands for Voltage output high and Vol isVoltage output low As a first approximation Voh is equal to the supply voltage and Vol is zero volts However asthe current increases the voltage drop across the output transistor will increase This results in the voltage being lessthan the supply voltage when the pin is set to a 1 and the output voltage being more than 0 volts when the output isset to a 0

If you try to sink or source large amounts of current the change in the output voltage can cause problems in yourcircuit operations A simple and practical rule of thumb is to find the current when Voh is 90 of the supply voltageand use that as your maximum Ioh Similarly find the current on the chart where Vol is 10 of the supply voltageand use it as the maximum Iol This will keep you out of trouble in most situations

It should be noted that some microcontrollers have a few IO pins that are open collector These donrsquot have the upper(red) transistor as shown in Figure 3-1 These will need external pull up resistors

SummaryA microcontroller IO pin can be set by the program to operate as an output The output voltage will be close to thesupply voltage when the output is set to a logical 1 The output voltage will be close to 0 volts when the pin is set to alogical 0

An output pin can either source or sink the current to or from a load It is important not to exceed the maximum currentratings which can be found in the microcontrollerrsquos data sheet

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Split Core Current Sensor wwwopensourcemetercom

Low Cost Current Transformers Get help specifyingyour solution

Dynamometer Crane Scales wwwcscforcecom

Safe for Overhead Use-High Accuracy Dial DigitalNew Used Rentals

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Dc dc converter design wwwcdiwebcomminmax

ACDC Power Modules Low Cost Great DeliveryStandard and Custom

Custom Pins - Free Quote wwwqualitylapelpinscom

Highest Quality at the Lowest Price Custom Pins aslow as $049 each

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin Thereis a maximum of 200ma total for the package About 25ma should be reserved for the internal operation of theATMega328 leaving about 175ma maximum current forthe rest of the IO pins

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 2Microcontroller Interfacing Part 4

Back to Electronics Main PageHome

Unified Microsystems for electronicequipment modules and kits forengineers electronic hobbyists andAmateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Lecroy Used OscilloscopesOrder securely 247 at TechRecovery InstockFully GuaranteedwwwTechRecoverycom

Digital OscilloscopesDigital Oscilloscopes now from RohdeampSchwarzGet Details Herewwwscope-of-the-artcomRTO

Habey USA BIS-6622Ultra-Conpact Fanless PCs Tunnel Creek IntelAtom E6xx serieswwwhabeyusacom

Custom Force TransducersDesign and manufacturing expertise Contact ustodaywwwhitecorpcomcustom-transducers

>

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 4Driving LED and Other Simple Loads

GoalsThis section describes how to drive an LED and other simple low current loads with a microcontroller output pin

LEDs are very commonly used as indicators on embedded systems When bringing up a new design getting theLED to flash is usually the first step in checking out the hardware When a new programmer writes his first programon a PC it is usually the famous ldquoHello worldrdquo program The embedded system equivalent is a flashing LED

LED characteristicsLEDs are diodes Diodes conduct current when they are forward biased LEDs giveoff light when a current flows through them The amount of light given off or itsbrightness will be proportional to the current The more current that is allowed to flowthe brighter it will get This will continue until you get one bright flash after which it nolonger emits light or acts as a diode for that matter

The data sheet for the LED will generally give the light output at some typical operatingcurrent You can operate the LED at a lower current and get less light or at a highercurrent and get more light as long as you donrsquot exceed the maximum ratings of theLED

Different LEDs will produce different amounts of lights for the same current Highefficiency LEDs will be brighter but will be more expensive than garden variety LEDs Small LEDs typically run at 15 to 25 ma while larger high output types may run100ma or more

Another important characteristic of an LED is the Vfwd or forward drop voltage Adiode has an exponential V-I curve As the current through the LED increases thevoltage drop across it will increase only slightly Vfwd will be listed at a specific currentusually the same one used for rating the light output

Vfwd will usually be around 2 volts for red LEDs and increase with different colorsBlue or white LEDs are often a bit over 3 volts Vfwd will be important for setting theproper current level for the LED

LED design exampleYour project will control a motor It will use an LED to indicate an over temperaturecondition A second identical LED will indicate an over speed condition You select ared LED and look up the specs in the data sheet The luminosity (light output) is whatyou want at the recommended current of 15 ma The voltage drop at that current is 19volts

Figure 4-1 shows the two LEDs being driven in different ways LED1 is uses themicrocontroller output pin P0 as a sink and LED2 uses the pin P1 as a source Youwill note a resistor in series with the LEDs If you were to omit the resistor and drovethe LED directly with the microcontroller pin excessive current would flow when youturned on the LED probably burning out that pin on the microcontroller or maybe the

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

PCB Load CellsStrain guage LoadCells LifetimeWarranty Pluswwwpcbloadtorquecom

Custom ForceTransducersDesign andmanufacturingexpertise Contact ustodaywwwhitecorpcomcustom-hellip

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

LED The question is what value should we use for the resistor

We will use the LED1-R1 combination to do thecalculation The source voltage is 5V from our supplyThe voltage dropped across the LED is 19 which wefound in the data sheet Since the voltage around thecircuit loop must be zero volts

Vdd = Vr + Vfwd

Rearranging the terms gives us

Vr = Vdd ndash Vfwd = 5 ndash 19 = 31 V

We now know the voltage across the resistor is 31Vand we decided earlier that we wanted to drive the LEDat 15ma so a simple application of Ohmrsquos Law will tell uswhat value resistor is needed

R = VI = 31015 = 207 ohms

Resistors come in standard values The closest 5resistor values are 200 ohm and 220 ohm Either wouldbe OK The 200 ohm would result in a little more than15ma of current and the 220 ohm resistor would be lessthan 15ma

The value for R2 is the same as R1 The only realdifference is the microcontroller is supplying 5 voltsinstead of directly getting it from the power supply

Sink or SourceWhich one should you use In most cases it is a matterof personal preference To turn on LED 1 you need toset the PO register bit to a zero To turn on LED2 youset P1 to a logical 1 To many developers setting a pinto a 1 or high seems more natural for turning somethingon so you might want to use the microcontroller pin as asource

One case you might need to use one driving methodover another is when the maximum source and sinkcurrents are not the same and only one method will beable to handle the current needed

If the pin you selected is an open drain type you willneed to sink the current Open drain outputs do not havean internal transistor to Vdd so the pin canrsquot supplycurrent Some microcontrollers have a few IO pins thatare open drain

SummaryControlling an LED with a microcontroller is a commonapplication and is easy to implement Make sure thatcurrent limits of the microcontroller and LED are notexceeded

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

Electronic LEDSigns30 years of LEDexperience offeringcustom LED SignsolutionswwwDataDisplayUsacom

Led display drivericPink is the New GreenZMDI ProductsAvailable at CDIwwwcdiwebcomzmdi

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Super Bright LEDsLarge Selection ofRigid Flexible AndRGB LED Light BarsBuy OnlinesuperbrightledscomRigidLhellip

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

High voltage dc dcACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Paver Lights fromGermanyUL listed IP68 drive-over LED A newstandard for ingroundlightswwwjobe-lightingcom

Enclosure LEDLightingManufactured in NorthAmerica ExplosionProof Low Profilewwwnemaluxcom

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Figure 4-1

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Microcontroller Kits wwwATRIATechnologiescom

8 32 bit LCD USB Order NOW Starting At $79 -Shop On Line

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulation

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 2: Micro Controller Interfacing

Microcontroller Interfacing - Introduction

httpwwww9xtcompage_microdesign_pt1_introhtml[27062011 13334 PM]

Created with the QTHcom SiteBuilder

special tips for Arduino users are included on some topic pages

Note that the series may not follow a logical order Sections are added as Iget the urge or based on requests from readers Rather than re-sortingthem from time to time I decided to leave them in the order they are writtenso that external links to these pages are not affected

Im always looking for feedback on this series Please contact me if you findany errors If there is a specific topic you would like covered please sendme an email and I will put it on the list for consideration for futureinstallments Email w9xt (at) unifiedmicro (dot) com Be sure to includeldquoMicrocontroller IF Seriesrdquo in the subject line so it will not be caught in thespam filter

Enjoy your journey into the world of embedded systems

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 2

Back to Electronics Main PageHome Page

Unified Microsystems Electronic equipmentmodules and kits for engineers studentselectronic hobbyists and Amateur Radiooperators

copy 2009 - 2011 Gary C Sutcliffe

searchable PDF Senddocument directly intoDMSECMwwwomtoolcomAccuRoute

Habey USA BIS-6622Ultra-Conpact FanlessPCs Tunnel CreekIntel Atom E6xx serieswwwhabeyusacom

ApplicationsIntegrationGo Open Source ForYour ApplicationIntegration FreeProduct DownloadwwwtalendcomFree_Intehellip

Microcontroller Interfacing - Basic Electronics

httpwwww9xtcompage_microdesign_pt2_basic_electhtml[27062011 13404 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 2Basic Electricity Review

GoalThis section covers some basics of electricity It is assumed that the reader has a basic knowledge of electronics andthis is a quick review

Ohmrsquos Law

Figure 2-1 shows the simplest circuit possible It consists of a voltage source and a single resistor The voltagesource is DC in this case Unless otherwise noted we will be dealing exclusively with DC voltage in this series Inmicrocontroller circuits the power source will usually be a power supply or battery In most cases the voltages wewill be working with will be 12 volts or less

With a given voltage (V) and resistor value (R) a given current (I) will flow A simple equation Ohmrsquos Law gives therelationship between voltage resistance and current

V = I RSimple algebra lets us manipulate the equation to solve for the unknown variable

I = VR or R = VI

In Figure 2-1 if we know our voltage source is 5V and we have a 1000 ohmresistor we can calculate the current in amperes

I = VR = 51000 = 005 A more often stated as 5 ma

In designing circuits we often have a given value for one parameter of V R orI and a desired value for one of the other variables The goal is to select theremaining component to give provide the desired value For example supposewe have a 12 V battery and want 65 ma of current What resistor value do weneed

R = VI = 12065 = 1846 ohms

Now finding a 1846 ohm resistor is going to be difficult but fortunately in mostcases you do not need (and are unable) to get that sort of precision Theclosest standard 5 resistor is 180 ohms If we use a 180 ohm resistor and itis right on 180 ohms (it wonrsquot be) we will get the following current

I = VR = 12180 = 067 A or 67 ma In most cases this will be close enough Figure 2-1

Voltage DividersFigure 2-2 shows a slightly more complex circuit one that has a voltagesource and two resistors There are several points to illustrate with sucha circuit The first is that resistors in series have a total resistance equalto the sum of the individual resistances

Microcontroller Interfacing - Basic Electronics

httpwwww9xtcompage_microdesign_pt2_basic_electhtml[27062011 13404 PM]

What would the current be in the circuit shown in Figure 2-2 be Sincethe two resistors could be substituted by a single resistor with a valueequal to the sum of the two Ohmrsquos Law states

I = V(R1 + R2)The other important point is to realize the there will be a voltage acrosseach component in the circuit If you put a voltmeter across the powersource you would read Vs Measuring across R1 you would measurevoltage V1 Voltage V2 would appear across R2

Note the polarity of the voltages with reference to the arrow indicatingcurrent The ones across the resistors are opposite polarity of thevoltage source This is because the net voltage around the loop must bezero Mathematically the voltages follow this equation

Vs = V1 + V2So what are the voltages V1 and V2 That depends on the ratio of thevalues of R1 and R2 The voltage across a resistor will be proportional tothe value of that resistor compared to the total The following equationsapply

V1 = Vs R1(R1+R2) V2 = Vs R2(R1+ R2)If we had three resistors in the circuit the following would apply

V1 = Vs R1(R1+R2+R3)

Suppose Vs = 12V R1 = 1200Ω and R2 = 2400Ω What is the voltageacross each resistor

V1 = Vs R1(R1+R2) = 12 1200(1200 +2400) = 4 V

To calculate the voltage across R2 we could use the equation for V2 orwe could apply the knowledge that the total voltage across the loop mustequal 0V

Vs = V1 + V2 --gt V2 = Vs - V1 = 12- 4 = 8V

SummaryDesigning interface circuits to microcontrollers requires some simplemathematics Understanding Ohmrsquos Law and voltage dividers will covera large percentage of the situations for simple circuits

Figure 2-2

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Flexible PrintedCircuitsFlexible Printed CircuitBoards Quick Turn ampFlex Circuit Assemblywwwallflexinccom

Electric circuitsanswersElectric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

PCB - IntroductoryOffer2 Layers $25ea - 4Layers $50ea Even 1piece is Ok - NoToolingwwwPCBnetcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relay

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 1Microcontroller Interfacing Part 3

Microcontroller Interfacing - Basic Electronics

httpwwww9xtcompage_microdesign_pt2_basic_electhtml[27062011 13404 PM]

Created with the QTHcom SiteBuilder

Back to Electronics Main PageHome Page

assembliesanaconpowercom

copy 2009 - 2011 Gary C Sutcliffe

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

Electric circuits 9Electric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Real TimeEmbedded SystemLeaders in EmbeddedSubsystems For ISRApplications LearnMorewwwmccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Electric circuits 9Electric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

Analyze EmbeddedCodeFind and fix criticalbugs with CodeSonarFree evaluationwwwGrammaTechcom

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 3Microcontroller Digital Output Basics

GoalThis section goes over the basics of microcontroller output ports It will cover how they can be used to interface to theoutside world and some of the limitations A separate section will cover use of microcontroller IO pins as inputs

Digital IO PortsMicrocontrollers generally combine their output pins into 8 bit ports Op code instructions allow easy manipulations ofthe values as a byte Byte operations are convenient when all 8 bits are part of a data byte At other times you willwant use each bit for a different specific purpose You might want one bit to control an LED a couple more to controlrelays etc There will be op code instructions that let you manipulate individual bits If you program in C Basic orother high level language the compiler will have instructions for controlling individual bits

Most IO pins on a microcontroller can be set as digital inputs or outputs You will want to configure them in the desireddirection early in the software that is executed when the microcontroller is powered up or reset There will be specialregisters for this purpose

The individual pins of an output port can have one of twooutput voltages depending on how the bit is set in the portrsquosoutput register If the bit is set to a ldquo1rdquo the output pin willhave a high voltage The value of the voltage will usuallybe the same as the microcontrollerrsquos supply voltageSometimes setting a bit to a 1 is also called setting it highor just setting the bit Depending on the system design thiswill usually be 33V or 5V Some new microcontrollerdesigned for low power battery applications run at lowervoltages

If the output pin is set to a ldquo0rdquo the voltage at the pin will beclose to zero volts This is also called clearing the bit orsetting it low

The different voltages are obtained by internal transistorsthat switch the output pin to the supply voltage or groundFigure 3-1 is a simplified diagram of an output pinarbitrarily labeled P0 for this example

The red transistor will be on when the output is set to alogical lsquo1rsquo Output pin P0 will be connected to +5V in thisexample If the output is set to a logical lsquo0rsquo the bluetransistor will be on connecting the output pin to ground or0V Only one of the two transistors can be on at a time Both transistors will be off if the pin is configured as aninput and in some other special conditions but one of thetwo will be on if the pin is configured as an output

Driving LoadsAn output pin not connected to anything is not of much

Figure 3-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

interest To do something useful it must be connected toanother device referred here simply as a ldquoloadrdquo A realworld load could be an LED a lamp a transistor or someother circuit element

Generally there are two ways to connect an output pin to aload The first is where the microcontroller supplies thecurrent to drive the device The microcontroller is referredto as the source Current flows from the microcontrollerpower to the output pin through the load and to groundThis configuration is shown in Figure 3-2a

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

The microcontroller pin can also ldquosinkrdquo the current asshown in Figure 3-2b Here the current flows fromthe power supply through the load and through theoutput pin to ground It is important that the load beconnected to the same power supply line as themicrocontroller or you can destroy the IC

Output CurrentsMicrocontrollers are somewhat delicate devices andthe IO lines can only carry a relatively small amountof current The current limit will depend on the typeof microcontroller and the specific pin There willusually be a maximum total current the pins of asingle 8 bit port can handle as well as a limit for allof the outputs for the entire microcontrollerExceeding the limits will destroy the microcontroller

To find out what the maximum currents are youneed to look at the data sheet for the microcontrollerPDF formatted data sheets can be downloaded fromthe manufacturer These can be quite large several

Figure 3-2

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Buy Electronic LED Sign wwwMegaSignInccom

Spend Less On Top Quality Long LastingProgrammable LED Order Now

Pro Energy wwwproenergyca

Rental Power Solutions Generators LightsElectrical Dist

Solid State Relays anaconpowercom

Manufacturer of DIN and Panel mount solid staterelay assemblies

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

hundred pages for a fairly complex one Look for asection titled ldquoElectrical Specificationsrdquo or somethingsimilar Usually in the section there will be a tablecalled ldquoAbsolute Maximum Ratingsrdquo or similar Youwill find a table containing a number of specificationsincluding

Characteristic Symbol ValueOutput Source Current

Ioh -25ma

Output Sink Current Iol 25ma

Ioh stands for Current (I) output high Iol stands for current output low Currents are traditionally referenced as goinginto a pin If the output is high the current flows out so it is given a negative number In some microcontrollers themaximum sink and source current limits for a given pin might be different You will also want to check the portion ofthe data sheet that covers the port you are using Some ports have more drive capacity than others on somemicrocontrollers Exceptions will be spelled out there

Some manufacturers such as Atmel will not give a single value for the maximum current allowed for output pinsInstead they provide a graph that plots the Voh vs Ioh and Vol vs Iol Voh stands for Voltage output high and Vol isVoltage output low As a first approximation Voh is equal to the supply voltage and Vol is zero volts However asthe current increases the voltage drop across the output transistor will increase This results in the voltage being lessthan the supply voltage when the pin is set to a 1 and the output voltage being more than 0 volts when the output isset to a 0

If you try to sink or source large amounts of current the change in the output voltage can cause problems in yourcircuit operations A simple and practical rule of thumb is to find the current when Voh is 90 of the supply voltageand use that as your maximum Ioh Similarly find the current on the chart where Vol is 10 of the supply voltageand use it as the maximum Iol This will keep you out of trouble in most situations

It should be noted that some microcontrollers have a few IO pins that are open collector These donrsquot have the upper(red) transistor as shown in Figure 3-1 These will need external pull up resistors

SummaryA microcontroller IO pin can be set by the program to operate as an output The output voltage will be close to thesupply voltage when the output is set to a logical 1 The output voltage will be close to 0 volts when the pin is set to alogical 0

An output pin can either source or sink the current to or from a load It is important not to exceed the maximum currentratings which can be found in the microcontrollerrsquos data sheet

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Split Core Current Sensor wwwopensourcemetercom

Low Cost Current Transformers Get help specifyingyour solution

Dynamometer Crane Scales wwwcscforcecom

Safe for Overhead Use-High Accuracy Dial DigitalNew Used Rentals

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Dc dc converter design wwwcdiwebcomminmax

ACDC Power Modules Low Cost Great DeliveryStandard and Custom

Custom Pins - Free Quote wwwqualitylapelpinscom

Highest Quality at the Lowest Price Custom Pins aslow as $049 each

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin Thereis a maximum of 200ma total for the package About 25ma should be reserved for the internal operation of theATMega328 leaving about 175ma maximum current forthe rest of the IO pins

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 2Microcontroller Interfacing Part 4

Back to Electronics Main PageHome

Unified Microsystems for electronicequipment modules and kits forengineers electronic hobbyists andAmateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Lecroy Used OscilloscopesOrder securely 247 at TechRecovery InstockFully GuaranteedwwwTechRecoverycom

Digital OscilloscopesDigital Oscilloscopes now from RohdeampSchwarzGet Details Herewwwscope-of-the-artcomRTO

Habey USA BIS-6622Ultra-Conpact Fanless PCs Tunnel Creek IntelAtom E6xx serieswwwhabeyusacom

Custom Force TransducersDesign and manufacturing expertise Contact ustodaywwwhitecorpcomcustom-transducers

>

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 4Driving LED and Other Simple Loads

GoalsThis section describes how to drive an LED and other simple low current loads with a microcontroller output pin

LEDs are very commonly used as indicators on embedded systems When bringing up a new design getting theLED to flash is usually the first step in checking out the hardware When a new programmer writes his first programon a PC it is usually the famous ldquoHello worldrdquo program The embedded system equivalent is a flashing LED

LED characteristicsLEDs are diodes Diodes conduct current when they are forward biased LEDs giveoff light when a current flows through them The amount of light given off or itsbrightness will be proportional to the current The more current that is allowed to flowthe brighter it will get This will continue until you get one bright flash after which it nolonger emits light or acts as a diode for that matter

The data sheet for the LED will generally give the light output at some typical operatingcurrent You can operate the LED at a lower current and get less light or at a highercurrent and get more light as long as you donrsquot exceed the maximum ratings of theLED

Different LEDs will produce different amounts of lights for the same current Highefficiency LEDs will be brighter but will be more expensive than garden variety LEDs Small LEDs typically run at 15 to 25 ma while larger high output types may run100ma or more

Another important characteristic of an LED is the Vfwd or forward drop voltage Adiode has an exponential V-I curve As the current through the LED increases thevoltage drop across it will increase only slightly Vfwd will be listed at a specific currentusually the same one used for rating the light output

Vfwd will usually be around 2 volts for red LEDs and increase with different colorsBlue or white LEDs are often a bit over 3 volts Vfwd will be important for setting theproper current level for the LED

LED design exampleYour project will control a motor It will use an LED to indicate an over temperaturecondition A second identical LED will indicate an over speed condition You select ared LED and look up the specs in the data sheet The luminosity (light output) is whatyou want at the recommended current of 15 ma The voltage drop at that current is 19volts

Figure 4-1 shows the two LEDs being driven in different ways LED1 is uses themicrocontroller output pin P0 as a sink and LED2 uses the pin P1 as a source Youwill note a resistor in series with the LEDs If you were to omit the resistor and drovethe LED directly with the microcontroller pin excessive current would flow when youturned on the LED probably burning out that pin on the microcontroller or maybe the

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

PCB Load CellsStrain guage LoadCells LifetimeWarranty Pluswwwpcbloadtorquecom

Custom ForceTransducersDesign andmanufacturingexpertise Contact ustodaywwwhitecorpcomcustom-hellip

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

LED The question is what value should we use for the resistor

We will use the LED1-R1 combination to do thecalculation The source voltage is 5V from our supplyThe voltage dropped across the LED is 19 which wefound in the data sheet Since the voltage around thecircuit loop must be zero volts

Vdd = Vr + Vfwd

Rearranging the terms gives us

Vr = Vdd ndash Vfwd = 5 ndash 19 = 31 V

We now know the voltage across the resistor is 31Vand we decided earlier that we wanted to drive the LEDat 15ma so a simple application of Ohmrsquos Law will tell uswhat value resistor is needed

R = VI = 31015 = 207 ohms

Resistors come in standard values The closest 5resistor values are 200 ohm and 220 ohm Either wouldbe OK The 200 ohm would result in a little more than15ma of current and the 220 ohm resistor would be lessthan 15ma

The value for R2 is the same as R1 The only realdifference is the microcontroller is supplying 5 voltsinstead of directly getting it from the power supply

Sink or SourceWhich one should you use In most cases it is a matterof personal preference To turn on LED 1 you need toset the PO register bit to a zero To turn on LED2 youset P1 to a logical 1 To many developers setting a pinto a 1 or high seems more natural for turning somethingon so you might want to use the microcontroller pin as asource

One case you might need to use one driving methodover another is when the maximum source and sinkcurrents are not the same and only one method will beable to handle the current needed

If the pin you selected is an open drain type you willneed to sink the current Open drain outputs do not havean internal transistor to Vdd so the pin canrsquot supplycurrent Some microcontrollers have a few IO pins thatare open drain

SummaryControlling an LED with a microcontroller is a commonapplication and is easy to implement Make sure thatcurrent limits of the microcontroller and LED are notexceeded

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

Electronic LEDSigns30 years of LEDexperience offeringcustom LED SignsolutionswwwDataDisplayUsacom

Led display drivericPink is the New GreenZMDI ProductsAvailable at CDIwwwcdiwebcomzmdi

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Super Bright LEDsLarge Selection ofRigid Flexible AndRGB LED Light BarsBuy OnlinesuperbrightledscomRigidLhellip

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

High voltage dc dcACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Paver Lights fromGermanyUL listed IP68 drive-over LED A newstandard for ingroundlightswwwjobe-lightingcom

Enclosure LEDLightingManufactured in NorthAmerica ExplosionProof Low Profilewwwnemaluxcom

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Figure 4-1

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Microcontroller Kits wwwATRIATechnologiescom

8 32 bit LCD USB Order NOW Starting At $79 -Shop On Line

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulation

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 3: Micro Controller Interfacing

Microcontroller Interfacing - Basic Electronics

httpwwww9xtcompage_microdesign_pt2_basic_electhtml[27062011 13404 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 2Basic Electricity Review

GoalThis section covers some basics of electricity It is assumed that the reader has a basic knowledge of electronics andthis is a quick review

Ohmrsquos Law

Figure 2-1 shows the simplest circuit possible It consists of a voltage source and a single resistor The voltagesource is DC in this case Unless otherwise noted we will be dealing exclusively with DC voltage in this series Inmicrocontroller circuits the power source will usually be a power supply or battery In most cases the voltages wewill be working with will be 12 volts or less

With a given voltage (V) and resistor value (R) a given current (I) will flow A simple equation Ohmrsquos Law gives therelationship between voltage resistance and current

V = I RSimple algebra lets us manipulate the equation to solve for the unknown variable

I = VR or R = VI

In Figure 2-1 if we know our voltage source is 5V and we have a 1000 ohmresistor we can calculate the current in amperes

I = VR = 51000 = 005 A more often stated as 5 ma

In designing circuits we often have a given value for one parameter of V R orI and a desired value for one of the other variables The goal is to select theremaining component to give provide the desired value For example supposewe have a 12 V battery and want 65 ma of current What resistor value do weneed

R = VI = 12065 = 1846 ohms

Now finding a 1846 ohm resistor is going to be difficult but fortunately in mostcases you do not need (and are unable) to get that sort of precision Theclosest standard 5 resistor is 180 ohms If we use a 180 ohm resistor and itis right on 180 ohms (it wonrsquot be) we will get the following current

I = VR = 12180 = 067 A or 67 ma In most cases this will be close enough Figure 2-1

Voltage DividersFigure 2-2 shows a slightly more complex circuit one that has a voltagesource and two resistors There are several points to illustrate with sucha circuit The first is that resistors in series have a total resistance equalto the sum of the individual resistances

Microcontroller Interfacing - Basic Electronics

httpwwww9xtcompage_microdesign_pt2_basic_electhtml[27062011 13404 PM]

What would the current be in the circuit shown in Figure 2-2 be Sincethe two resistors could be substituted by a single resistor with a valueequal to the sum of the two Ohmrsquos Law states

I = V(R1 + R2)The other important point is to realize the there will be a voltage acrosseach component in the circuit If you put a voltmeter across the powersource you would read Vs Measuring across R1 you would measurevoltage V1 Voltage V2 would appear across R2

Note the polarity of the voltages with reference to the arrow indicatingcurrent The ones across the resistors are opposite polarity of thevoltage source This is because the net voltage around the loop must bezero Mathematically the voltages follow this equation

Vs = V1 + V2So what are the voltages V1 and V2 That depends on the ratio of thevalues of R1 and R2 The voltage across a resistor will be proportional tothe value of that resistor compared to the total The following equationsapply

V1 = Vs R1(R1+R2) V2 = Vs R2(R1+ R2)If we had three resistors in the circuit the following would apply

V1 = Vs R1(R1+R2+R3)

Suppose Vs = 12V R1 = 1200Ω and R2 = 2400Ω What is the voltageacross each resistor

V1 = Vs R1(R1+R2) = 12 1200(1200 +2400) = 4 V

To calculate the voltage across R2 we could use the equation for V2 orwe could apply the knowledge that the total voltage across the loop mustequal 0V

Vs = V1 + V2 --gt V2 = Vs - V1 = 12- 4 = 8V

SummaryDesigning interface circuits to microcontrollers requires some simplemathematics Understanding Ohmrsquos Law and voltage dividers will covera large percentage of the situations for simple circuits

Figure 2-2

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Flexible PrintedCircuitsFlexible Printed CircuitBoards Quick Turn ampFlex Circuit Assemblywwwallflexinccom

Electric circuitsanswersElectric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

PCB - IntroductoryOffer2 Layers $25ea - 4Layers $50ea Even 1piece is Ok - NoToolingwwwPCBnetcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relay

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 1Microcontroller Interfacing Part 3

Microcontroller Interfacing - Basic Electronics

httpwwww9xtcompage_microdesign_pt2_basic_electhtml[27062011 13404 PM]

Created with the QTHcom SiteBuilder

Back to Electronics Main PageHome Page

assembliesanaconpowercom

copy 2009 - 2011 Gary C Sutcliffe

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

Electric circuits 9Electric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Real TimeEmbedded SystemLeaders in EmbeddedSubsystems For ISRApplications LearnMorewwwmccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Electric circuits 9Electric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

Analyze EmbeddedCodeFind and fix criticalbugs with CodeSonarFree evaluationwwwGrammaTechcom

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 3Microcontroller Digital Output Basics

GoalThis section goes over the basics of microcontroller output ports It will cover how they can be used to interface to theoutside world and some of the limitations A separate section will cover use of microcontroller IO pins as inputs

Digital IO PortsMicrocontrollers generally combine their output pins into 8 bit ports Op code instructions allow easy manipulations ofthe values as a byte Byte operations are convenient when all 8 bits are part of a data byte At other times you willwant use each bit for a different specific purpose You might want one bit to control an LED a couple more to controlrelays etc There will be op code instructions that let you manipulate individual bits If you program in C Basic orother high level language the compiler will have instructions for controlling individual bits

Most IO pins on a microcontroller can be set as digital inputs or outputs You will want to configure them in the desireddirection early in the software that is executed when the microcontroller is powered up or reset There will be specialregisters for this purpose

The individual pins of an output port can have one of twooutput voltages depending on how the bit is set in the portrsquosoutput register If the bit is set to a ldquo1rdquo the output pin willhave a high voltage The value of the voltage will usuallybe the same as the microcontrollerrsquos supply voltageSometimes setting a bit to a 1 is also called setting it highor just setting the bit Depending on the system design thiswill usually be 33V or 5V Some new microcontrollerdesigned for low power battery applications run at lowervoltages

If the output pin is set to a ldquo0rdquo the voltage at the pin will beclose to zero volts This is also called clearing the bit orsetting it low

The different voltages are obtained by internal transistorsthat switch the output pin to the supply voltage or groundFigure 3-1 is a simplified diagram of an output pinarbitrarily labeled P0 for this example

The red transistor will be on when the output is set to alogical lsquo1rsquo Output pin P0 will be connected to +5V in thisexample If the output is set to a logical lsquo0rsquo the bluetransistor will be on connecting the output pin to ground or0V Only one of the two transistors can be on at a time Both transistors will be off if the pin is configured as aninput and in some other special conditions but one of thetwo will be on if the pin is configured as an output

Driving LoadsAn output pin not connected to anything is not of much

Figure 3-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

interest To do something useful it must be connected toanother device referred here simply as a ldquoloadrdquo A realworld load could be an LED a lamp a transistor or someother circuit element

Generally there are two ways to connect an output pin to aload The first is where the microcontroller supplies thecurrent to drive the device The microcontroller is referredto as the source Current flows from the microcontrollerpower to the output pin through the load and to groundThis configuration is shown in Figure 3-2a

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

The microcontroller pin can also ldquosinkrdquo the current asshown in Figure 3-2b Here the current flows fromthe power supply through the load and through theoutput pin to ground It is important that the load beconnected to the same power supply line as themicrocontroller or you can destroy the IC

Output CurrentsMicrocontrollers are somewhat delicate devices andthe IO lines can only carry a relatively small amountof current The current limit will depend on the typeof microcontroller and the specific pin There willusually be a maximum total current the pins of asingle 8 bit port can handle as well as a limit for allof the outputs for the entire microcontrollerExceeding the limits will destroy the microcontroller

To find out what the maximum currents are youneed to look at the data sheet for the microcontrollerPDF formatted data sheets can be downloaded fromthe manufacturer These can be quite large several

Figure 3-2

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Buy Electronic LED Sign wwwMegaSignInccom

Spend Less On Top Quality Long LastingProgrammable LED Order Now

Pro Energy wwwproenergyca

Rental Power Solutions Generators LightsElectrical Dist

Solid State Relays anaconpowercom

Manufacturer of DIN and Panel mount solid staterelay assemblies

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

hundred pages for a fairly complex one Look for asection titled ldquoElectrical Specificationsrdquo or somethingsimilar Usually in the section there will be a tablecalled ldquoAbsolute Maximum Ratingsrdquo or similar Youwill find a table containing a number of specificationsincluding

Characteristic Symbol ValueOutput Source Current

Ioh -25ma

Output Sink Current Iol 25ma

Ioh stands for Current (I) output high Iol stands for current output low Currents are traditionally referenced as goinginto a pin If the output is high the current flows out so it is given a negative number In some microcontrollers themaximum sink and source current limits for a given pin might be different You will also want to check the portion ofthe data sheet that covers the port you are using Some ports have more drive capacity than others on somemicrocontrollers Exceptions will be spelled out there

Some manufacturers such as Atmel will not give a single value for the maximum current allowed for output pinsInstead they provide a graph that plots the Voh vs Ioh and Vol vs Iol Voh stands for Voltage output high and Vol isVoltage output low As a first approximation Voh is equal to the supply voltage and Vol is zero volts However asthe current increases the voltage drop across the output transistor will increase This results in the voltage being lessthan the supply voltage when the pin is set to a 1 and the output voltage being more than 0 volts when the output isset to a 0

If you try to sink or source large amounts of current the change in the output voltage can cause problems in yourcircuit operations A simple and practical rule of thumb is to find the current when Voh is 90 of the supply voltageand use that as your maximum Ioh Similarly find the current on the chart where Vol is 10 of the supply voltageand use it as the maximum Iol This will keep you out of trouble in most situations

It should be noted that some microcontrollers have a few IO pins that are open collector These donrsquot have the upper(red) transistor as shown in Figure 3-1 These will need external pull up resistors

SummaryA microcontroller IO pin can be set by the program to operate as an output The output voltage will be close to thesupply voltage when the output is set to a logical 1 The output voltage will be close to 0 volts when the pin is set to alogical 0

An output pin can either source or sink the current to or from a load It is important not to exceed the maximum currentratings which can be found in the microcontrollerrsquos data sheet

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Split Core Current Sensor wwwopensourcemetercom

Low Cost Current Transformers Get help specifyingyour solution

Dynamometer Crane Scales wwwcscforcecom

Safe for Overhead Use-High Accuracy Dial DigitalNew Used Rentals

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Dc dc converter design wwwcdiwebcomminmax

ACDC Power Modules Low Cost Great DeliveryStandard and Custom

Custom Pins - Free Quote wwwqualitylapelpinscom

Highest Quality at the Lowest Price Custom Pins aslow as $049 each

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin Thereis a maximum of 200ma total for the package About 25ma should be reserved for the internal operation of theATMega328 leaving about 175ma maximum current forthe rest of the IO pins

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 2Microcontroller Interfacing Part 4

Back to Electronics Main PageHome

Unified Microsystems for electronicequipment modules and kits forengineers electronic hobbyists andAmateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Lecroy Used OscilloscopesOrder securely 247 at TechRecovery InstockFully GuaranteedwwwTechRecoverycom

Digital OscilloscopesDigital Oscilloscopes now from RohdeampSchwarzGet Details Herewwwscope-of-the-artcomRTO

Habey USA BIS-6622Ultra-Conpact Fanless PCs Tunnel Creek IntelAtom E6xx serieswwwhabeyusacom

Custom Force TransducersDesign and manufacturing expertise Contact ustodaywwwhitecorpcomcustom-transducers

>

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 4Driving LED and Other Simple Loads

GoalsThis section describes how to drive an LED and other simple low current loads with a microcontroller output pin

LEDs are very commonly used as indicators on embedded systems When bringing up a new design getting theLED to flash is usually the first step in checking out the hardware When a new programmer writes his first programon a PC it is usually the famous ldquoHello worldrdquo program The embedded system equivalent is a flashing LED

LED characteristicsLEDs are diodes Diodes conduct current when they are forward biased LEDs giveoff light when a current flows through them The amount of light given off or itsbrightness will be proportional to the current The more current that is allowed to flowthe brighter it will get This will continue until you get one bright flash after which it nolonger emits light or acts as a diode for that matter

The data sheet for the LED will generally give the light output at some typical operatingcurrent You can operate the LED at a lower current and get less light or at a highercurrent and get more light as long as you donrsquot exceed the maximum ratings of theLED

Different LEDs will produce different amounts of lights for the same current Highefficiency LEDs will be brighter but will be more expensive than garden variety LEDs Small LEDs typically run at 15 to 25 ma while larger high output types may run100ma or more

Another important characteristic of an LED is the Vfwd or forward drop voltage Adiode has an exponential V-I curve As the current through the LED increases thevoltage drop across it will increase only slightly Vfwd will be listed at a specific currentusually the same one used for rating the light output

Vfwd will usually be around 2 volts for red LEDs and increase with different colorsBlue or white LEDs are often a bit over 3 volts Vfwd will be important for setting theproper current level for the LED

LED design exampleYour project will control a motor It will use an LED to indicate an over temperaturecondition A second identical LED will indicate an over speed condition You select ared LED and look up the specs in the data sheet The luminosity (light output) is whatyou want at the recommended current of 15 ma The voltage drop at that current is 19volts

Figure 4-1 shows the two LEDs being driven in different ways LED1 is uses themicrocontroller output pin P0 as a sink and LED2 uses the pin P1 as a source Youwill note a resistor in series with the LEDs If you were to omit the resistor and drovethe LED directly with the microcontroller pin excessive current would flow when youturned on the LED probably burning out that pin on the microcontroller or maybe the

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

PCB Load CellsStrain guage LoadCells LifetimeWarranty Pluswwwpcbloadtorquecom

Custom ForceTransducersDesign andmanufacturingexpertise Contact ustodaywwwhitecorpcomcustom-hellip

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

LED The question is what value should we use for the resistor

We will use the LED1-R1 combination to do thecalculation The source voltage is 5V from our supplyThe voltage dropped across the LED is 19 which wefound in the data sheet Since the voltage around thecircuit loop must be zero volts

Vdd = Vr + Vfwd

Rearranging the terms gives us

Vr = Vdd ndash Vfwd = 5 ndash 19 = 31 V

We now know the voltage across the resistor is 31Vand we decided earlier that we wanted to drive the LEDat 15ma so a simple application of Ohmrsquos Law will tell uswhat value resistor is needed

R = VI = 31015 = 207 ohms

Resistors come in standard values The closest 5resistor values are 200 ohm and 220 ohm Either wouldbe OK The 200 ohm would result in a little more than15ma of current and the 220 ohm resistor would be lessthan 15ma

The value for R2 is the same as R1 The only realdifference is the microcontroller is supplying 5 voltsinstead of directly getting it from the power supply

Sink or SourceWhich one should you use In most cases it is a matterof personal preference To turn on LED 1 you need toset the PO register bit to a zero To turn on LED2 youset P1 to a logical 1 To many developers setting a pinto a 1 or high seems more natural for turning somethingon so you might want to use the microcontroller pin as asource

One case you might need to use one driving methodover another is when the maximum source and sinkcurrents are not the same and only one method will beable to handle the current needed

If the pin you selected is an open drain type you willneed to sink the current Open drain outputs do not havean internal transistor to Vdd so the pin canrsquot supplycurrent Some microcontrollers have a few IO pins thatare open drain

SummaryControlling an LED with a microcontroller is a commonapplication and is easy to implement Make sure thatcurrent limits of the microcontroller and LED are notexceeded

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

Electronic LEDSigns30 years of LEDexperience offeringcustom LED SignsolutionswwwDataDisplayUsacom

Led display drivericPink is the New GreenZMDI ProductsAvailable at CDIwwwcdiwebcomzmdi

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Super Bright LEDsLarge Selection ofRigid Flexible AndRGB LED Light BarsBuy OnlinesuperbrightledscomRigidLhellip

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

High voltage dc dcACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Paver Lights fromGermanyUL listed IP68 drive-over LED A newstandard for ingroundlightswwwjobe-lightingcom

Enclosure LEDLightingManufactured in NorthAmerica ExplosionProof Low Profilewwwnemaluxcom

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Figure 4-1

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Microcontroller Kits wwwATRIATechnologiescom

8 32 bit LCD USB Order NOW Starting At $79 -Shop On Line

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulation

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 4: Micro Controller Interfacing

Microcontroller Interfacing - Basic Electronics

httpwwww9xtcompage_microdesign_pt2_basic_electhtml[27062011 13404 PM]

What would the current be in the circuit shown in Figure 2-2 be Sincethe two resistors could be substituted by a single resistor with a valueequal to the sum of the two Ohmrsquos Law states

I = V(R1 + R2)The other important point is to realize the there will be a voltage acrosseach component in the circuit If you put a voltmeter across the powersource you would read Vs Measuring across R1 you would measurevoltage V1 Voltage V2 would appear across R2

Note the polarity of the voltages with reference to the arrow indicatingcurrent The ones across the resistors are opposite polarity of thevoltage source This is because the net voltage around the loop must bezero Mathematically the voltages follow this equation

Vs = V1 + V2So what are the voltages V1 and V2 That depends on the ratio of thevalues of R1 and R2 The voltage across a resistor will be proportional tothe value of that resistor compared to the total The following equationsapply

V1 = Vs R1(R1+R2) V2 = Vs R2(R1+ R2)If we had three resistors in the circuit the following would apply

V1 = Vs R1(R1+R2+R3)

Suppose Vs = 12V R1 = 1200Ω and R2 = 2400Ω What is the voltageacross each resistor

V1 = Vs R1(R1+R2) = 12 1200(1200 +2400) = 4 V

To calculate the voltage across R2 we could use the equation for V2 orwe could apply the knowledge that the total voltage across the loop mustequal 0V

Vs = V1 + V2 --gt V2 = Vs - V1 = 12- 4 = 8V

SummaryDesigning interface circuits to microcontrollers requires some simplemathematics Understanding Ohmrsquos Law and voltage dividers will covera large percentage of the situations for simple circuits

Figure 2-2

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Flexible PrintedCircuitsFlexible Printed CircuitBoards Quick Turn ampFlex Circuit Assemblywwwallflexinccom

Electric circuitsanswersElectric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

PCB - IntroductoryOffer2 Layers $25ea - 4Layers $50ea Even 1piece is Ok - NoToolingwwwPCBnetcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relay

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 1Microcontroller Interfacing Part 3

Microcontroller Interfacing - Basic Electronics

httpwwww9xtcompage_microdesign_pt2_basic_electhtml[27062011 13404 PM]

Created with the QTHcom SiteBuilder

Back to Electronics Main PageHome Page

assembliesanaconpowercom

copy 2009 - 2011 Gary C Sutcliffe

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

Electric circuits 9Electric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Real TimeEmbedded SystemLeaders in EmbeddedSubsystems For ISRApplications LearnMorewwwmccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Electric circuits 9Electric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

Analyze EmbeddedCodeFind and fix criticalbugs with CodeSonarFree evaluationwwwGrammaTechcom

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 3Microcontroller Digital Output Basics

GoalThis section goes over the basics of microcontroller output ports It will cover how they can be used to interface to theoutside world and some of the limitations A separate section will cover use of microcontroller IO pins as inputs

Digital IO PortsMicrocontrollers generally combine their output pins into 8 bit ports Op code instructions allow easy manipulations ofthe values as a byte Byte operations are convenient when all 8 bits are part of a data byte At other times you willwant use each bit for a different specific purpose You might want one bit to control an LED a couple more to controlrelays etc There will be op code instructions that let you manipulate individual bits If you program in C Basic orother high level language the compiler will have instructions for controlling individual bits

Most IO pins on a microcontroller can be set as digital inputs or outputs You will want to configure them in the desireddirection early in the software that is executed when the microcontroller is powered up or reset There will be specialregisters for this purpose

The individual pins of an output port can have one of twooutput voltages depending on how the bit is set in the portrsquosoutput register If the bit is set to a ldquo1rdquo the output pin willhave a high voltage The value of the voltage will usuallybe the same as the microcontrollerrsquos supply voltageSometimes setting a bit to a 1 is also called setting it highor just setting the bit Depending on the system design thiswill usually be 33V or 5V Some new microcontrollerdesigned for low power battery applications run at lowervoltages

If the output pin is set to a ldquo0rdquo the voltage at the pin will beclose to zero volts This is also called clearing the bit orsetting it low

The different voltages are obtained by internal transistorsthat switch the output pin to the supply voltage or groundFigure 3-1 is a simplified diagram of an output pinarbitrarily labeled P0 for this example

The red transistor will be on when the output is set to alogical lsquo1rsquo Output pin P0 will be connected to +5V in thisexample If the output is set to a logical lsquo0rsquo the bluetransistor will be on connecting the output pin to ground or0V Only one of the two transistors can be on at a time Both transistors will be off if the pin is configured as aninput and in some other special conditions but one of thetwo will be on if the pin is configured as an output

Driving LoadsAn output pin not connected to anything is not of much

Figure 3-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

interest To do something useful it must be connected toanother device referred here simply as a ldquoloadrdquo A realworld load could be an LED a lamp a transistor or someother circuit element

Generally there are two ways to connect an output pin to aload The first is where the microcontroller supplies thecurrent to drive the device The microcontroller is referredto as the source Current flows from the microcontrollerpower to the output pin through the load and to groundThis configuration is shown in Figure 3-2a

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

The microcontroller pin can also ldquosinkrdquo the current asshown in Figure 3-2b Here the current flows fromthe power supply through the load and through theoutput pin to ground It is important that the load beconnected to the same power supply line as themicrocontroller or you can destroy the IC

Output CurrentsMicrocontrollers are somewhat delicate devices andthe IO lines can only carry a relatively small amountof current The current limit will depend on the typeof microcontroller and the specific pin There willusually be a maximum total current the pins of asingle 8 bit port can handle as well as a limit for allof the outputs for the entire microcontrollerExceeding the limits will destroy the microcontroller

To find out what the maximum currents are youneed to look at the data sheet for the microcontrollerPDF formatted data sheets can be downloaded fromthe manufacturer These can be quite large several

Figure 3-2

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Buy Electronic LED Sign wwwMegaSignInccom

Spend Less On Top Quality Long LastingProgrammable LED Order Now

Pro Energy wwwproenergyca

Rental Power Solutions Generators LightsElectrical Dist

Solid State Relays anaconpowercom

Manufacturer of DIN and Panel mount solid staterelay assemblies

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

hundred pages for a fairly complex one Look for asection titled ldquoElectrical Specificationsrdquo or somethingsimilar Usually in the section there will be a tablecalled ldquoAbsolute Maximum Ratingsrdquo or similar Youwill find a table containing a number of specificationsincluding

Characteristic Symbol ValueOutput Source Current

Ioh -25ma

Output Sink Current Iol 25ma

Ioh stands for Current (I) output high Iol stands for current output low Currents are traditionally referenced as goinginto a pin If the output is high the current flows out so it is given a negative number In some microcontrollers themaximum sink and source current limits for a given pin might be different You will also want to check the portion ofthe data sheet that covers the port you are using Some ports have more drive capacity than others on somemicrocontrollers Exceptions will be spelled out there

Some manufacturers such as Atmel will not give a single value for the maximum current allowed for output pinsInstead they provide a graph that plots the Voh vs Ioh and Vol vs Iol Voh stands for Voltage output high and Vol isVoltage output low As a first approximation Voh is equal to the supply voltage and Vol is zero volts However asthe current increases the voltage drop across the output transistor will increase This results in the voltage being lessthan the supply voltage when the pin is set to a 1 and the output voltage being more than 0 volts when the output isset to a 0

If you try to sink or source large amounts of current the change in the output voltage can cause problems in yourcircuit operations A simple and practical rule of thumb is to find the current when Voh is 90 of the supply voltageand use that as your maximum Ioh Similarly find the current on the chart where Vol is 10 of the supply voltageand use it as the maximum Iol This will keep you out of trouble in most situations

It should be noted that some microcontrollers have a few IO pins that are open collector These donrsquot have the upper(red) transistor as shown in Figure 3-1 These will need external pull up resistors

SummaryA microcontroller IO pin can be set by the program to operate as an output The output voltage will be close to thesupply voltage when the output is set to a logical 1 The output voltage will be close to 0 volts when the pin is set to alogical 0

An output pin can either source or sink the current to or from a load It is important not to exceed the maximum currentratings which can be found in the microcontrollerrsquos data sheet

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Split Core Current Sensor wwwopensourcemetercom

Low Cost Current Transformers Get help specifyingyour solution

Dynamometer Crane Scales wwwcscforcecom

Safe for Overhead Use-High Accuracy Dial DigitalNew Used Rentals

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Dc dc converter design wwwcdiwebcomminmax

ACDC Power Modules Low Cost Great DeliveryStandard and Custom

Custom Pins - Free Quote wwwqualitylapelpinscom

Highest Quality at the Lowest Price Custom Pins aslow as $049 each

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin Thereis a maximum of 200ma total for the package About 25ma should be reserved for the internal operation of theATMega328 leaving about 175ma maximum current forthe rest of the IO pins

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 2Microcontroller Interfacing Part 4

Back to Electronics Main PageHome

Unified Microsystems for electronicequipment modules and kits forengineers electronic hobbyists andAmateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Lecroy Used OscilloscopesOrder securely 247 at TechRecovery InstockFully GuaranteedwwwTechRecoverycom

Digital OscilloscopesDigital Oscilloscopes now from RohdeampSchwarzGet Details Herewwwscope-of-the-artcomRTO

Habey USA BIS-6622Ultra-Conpact Fanless PCs Tunnel Creek IntelAtom E6xx serieswwwhabeyusacom

Custom Force TransducersDesign and manufacturing expertise Contact ustodaywwwhitecorpcomcustom-transducers

>

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 4Driving LED and Other Simple Loads

GoalsThis section describes how to drive an LED and other simple low current loads with a microcontroller output pin

LEDs are very commonly used as indicators on embedded systems When bringing up a new design getting theLED to flash is usually the first step in checking out the hardware When a new programmer writes his first programon a PC it is usually the famous ldquoHello worldrdquo program The embedded system equivalent is a flashing LED

LED characteristicsLEDs are diodes Diodes conduct current when they are forward biased LEDs giveoff light when a current flows through them The amount of light given off or itsbrightness will be proportional to the current The more current that is allowed to flowthe brighter it will get This will continue until you get one bright flash after which it nolonger emits light or acts as a diode for that matter

The data sheet for the LED will generally give the light output at some typical operatingcurrent You can operate the LED at a lower current and get less light or at a highercurrent and get more light as long as you donrsquot exceed the maximum ratings of theLED

Different LEDs will produce different amounts of lights for the same current Highefficiency LEDs will be brighter but will be more expensive than garden variety LEDs Small LEDs typically run at 15 to 25 ma while larger high output types may run100ma or more

Another important characteristic of an LED is the Vfwd or forward drop voltage Adiode has an exponential V-I curve As the current through the LED increases thevoltage drop across it will increase only slightly Vfwd will be listed at a specific currentusually the same one used for rating the light output

Vfwd will usually be around 2 volts for red LEDs and increase with different colorsBlue or white LEDs are often a bit over 3 volts Vfwd will be important for setting theproper current level for the LED

LED design exampleYour project will control a motor It will use an LED to indicate an over temperaturecondition A second identical LED will indicate an over speed condition You select ared LED and look up the specs in the data sheet The luminosity (light output) is whatyou want at the recommended current of 15 ma The voltage drop at that current is 19volts

Figure 4-1 shows the two LEDs being driven in different ways LED1 is uses themicrocontroller output pin P0 as a sink and LED2 uses the pin P1 as a source Youwill note a resistor in series with the LEDs If you were to omit the resistor and drovethe LED directly with the microcontroller pin excessive current would flow when youturned on the LED probably burning out that pin on the microcontroller or maybe the

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

PCB Load CellsStrain guage LoadCells LifetimeWarranty Pluswwwpcbloadtorquecom

Custom ForceTransducersDesign andmanufacturingexpertise Contact ustodaywwwhitecorpcomcustom-hellip

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

LED The question is what value should we use for the resistor

We will use the LED1-R1 combination to do thecalculation The source voltage is 5V from our supplyThe voltage dropped across the LED is 19 which wefound in the data sheet Since the voltage around thecircuit loop must be zero volts

Vdd = Vr + Vfwd

Rearranging the terms gives us

Vr = Vdd ndash Vfwd = 5 ndash 19 = 31 V

We now know the voltage across the resistor is 31Vand we decided earlier that we wanted to drive the LEDat 15ma so a simple application of Ohmrsquos Law will tell uswhat value resistor is needed

R = VI = 31015 = 207 ohms

Resistors come in standard values The closest 5resistor values are 200 ohm and 220 ohm Either wouldbe OK The 200 ohm would result in a little more than15ma of current and the 220 ohm resistor would be lessthan 15ma

The value for R2 is the same as R1 The only realdifference is the microcontroller is supplying 5 voltsinstead of directly getting it from the power supply

Sink or SourceWhich one should you use In most cases it is a matterof personal preference To turn on LED 1 you need toset the PO register bit to a zero To turn on LED2 youset P1 to a logical 1 To many developers setting a pinto a 1 or high seems more natural for turning somethingon so you might want to use the microcontroller pin as asource

One case you might need to use one driving methodover another is when the maximum source and sinkcurrents are not the same and only one method will beable to handle the current needed

If the pin you selected is an open drain type you willneed to sink the current Open drain outputs do not havean internal transistor to Vdd so the pin canrsquot supplycurrent Some microcontrollers have a few IO pins thatare open drain

SummaryControlling an LED with a microcontroller is a commonapplication and is easy to implement Make sure thatcurrent limits of the microcontroller and LED are notexceeded

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

Electronic LEDSigns30 years of LEDexperience offeringcustom LED SignsolutionswwwDataDisplayUsacom

Led display drivericPink is the New GreenZMDI ProductsAvailable at CDIwwwcdiwebcomzmdi

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Super Bright LEDsLarge Selection ofRigid Flexible AndRGB LED Light BarsBuy OnlinesuperbrightledscomRigidLhellip

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

High voltage dc dcACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Paver Lights fromGermanyUL listed IP68 drive-over LED A newstandard for ingroundlightswwwjobe-lightingcom

Enclosure LEDLightingManufactured in NorthAmerica ExplosionProof Low Profilewwwnemaluxcom

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Figure 4-1

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Microcontroller Kits wwwATRIATechnologiescom

8 32 bit LCD USB Order NOW Starting At $79 -Shop On Line

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulation

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 5: Micro Controller Interfacing

Microcontroller Interfacing - Basic Electronics

httpwwww9xtcompage_microdesign_pt2_basic_electhtml[27062011 13404 PM]

Created with the QTHcom SiteBuilder

Back to Electronics Main PageHome Page

assembliesanaconpowercom

copy 2009 - 2011 Gary C Sutcliffe

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

Electric circuits 9Electric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Real TimeEmbedded SystemLeaders in EmbeddedSubsystems For ISRApplications LearnMorewwwmccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Electric circuits 9Electric Circuits 9thEdition Solutions ViewFreeCramstercomNilsson

Analyze EmbeddedCodeFind and fix criticalbugs with CodeSonarFree evaluationwwwGrammaTechcom

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 3Microcontroller Digital Output Basics

GoalThis section goes over the basics of microcontroller output ports It will cover how they can be used to interface to theoutside world and some of the limitations A separate section will cover use of microcontroller IO pins as inputs

Digital IO PortsMicrocontrollers generally combine their output pins into 8 bit ports Op code instructions allow easy manipulations ofthe values as a byte Byte operations are convenient when all 8 bits are part of a data byte At other times you willwant use each bit for a different specific purpose You might want one bit to control an LED a couple more to controlrelays etc There will be op code instructions that let you manipulate individual bits If you program in C Basic orother high level language the compiler will have instructions for controlling individual bits

Most IO pins on a microcontroller can be set as digital inputs or outputs You will want to configure them in the desireddirection early in the software that is executed when the microcontroller is powered up or reset There will be specialregisters for this purpose

The individual pins of an output port can have one of twooutput voltages depending on how the bit is set in the portrsquosoutput register If the bit is set to a ldquo1rdquo the output pin willhave a high voltage The value of the voltage will usuallybe the same as the microcontrollerrsquos supply voltageSometimes setting a bit to a 1 is also called setting it highor just setting the bit Depending on the system design thiswill usually be 33V or 5V Some new microcontrollerdesigned for low power battery applications run at lowervoltages

If the output pin is set to a ldquo0rdquo the voltage at the pin will beclose to zero volts This is also called clearing the bit orsetting it low

The different voltages are obtained by internal transistorsthat switch the output pin to the supply voltage or groundFigure 3-1 is a simplified diagram of an output pinarbitrarily labeled P0 for this example

The red transistor will be on when the output is set to alogical lsquo1rsquo Output pin P0 will be connected to +5V in thisexample If the output is set to a logical lsquo0rsquo the bluetransistor will be on connecting the output pin to ground or0V Only one of the two transistors can be on at a time Both transistors will be off if the pin is configured as aninput and in some other special conditions but one of thetwo will be on if the pin is configured as an output

Driving LoadsAn output pin not connected to anything is not of much

Figure 3-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

interest To do something useful it must be connected toanother device referred here simply as a ldquoloadrdquo A realworld load could be an LED a lamp a transistor or someother circuit element

Generally there are two ways to connect an output pin to aload The first is where the microcontroller supplies thecurrent to drive the device The microcontroller is referredto as the source Current flows from the microcontrollerpower to the output pin through the load and to groundThis configuration is shown in Figure 3-2a

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

The microcontroller pin can also ldquosinkrdquo the current asshown in Figure 3-2b Here the current flows fromthe power supply through the load and through theoutput pin to ground It is important that the load beconnected to the same power supply line as themicrocontroller or you can destroy the IC

Output CurrentsMicrocontrollers are somewhat delicate devices andthe IO lines can only carry a relatively small amountof current The current limit will depend on the typeof microcontroller and the specific pin There willusually be a maximum total current the pins of asingle 8 bit port can handle as well as a limit for allof the outputs for the entire microcontrollerExceeding the limits will destroy the microcontroller

To find out what the maximum currents are youneed to look at the data sheet for the microcontrollerPDF formatted data sheets can be downloaded fromthe manufacturer These can be quite large several

Figure 3-2

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Buy Electronic LED Sign wwwMegaSignInccom

Spend Less On Top Quality Long LastingProgrammable LED Order Now

Pro Energy wwwproenergyca

Rental Power Solutions Generators LightsElectrical Dist

Solid State Relays anaconpowercom

Manufacturer of DIN and Panel mount solid staterelay assemblies

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

hundred pages for a fairly complex one Look for asection titled ldquoElectrical Specificationsrdquo or somethingsimilar Usually in the section there will be a tablecalled ldquoAbsolute Maximum Ratingsrdquo or similar Youwill find a table containing a number of specificationsincluding

Characteristic Symbol ValueOutput Source Current

Ioh -25ma

Output Sink Current Iol 25ma

Ioh stands for Current (I) output high Iol stands for current output low Currents are traditionally referenced as goinginto a pin If the output is high the current flows out so it is given a negative number In some microcontrollers themaximum sink and source current limits for a given pin might be different You will also want to check the portion ofthe data sheet that covers the port you are using Some ports have more drive capacity than others on somemicrocontrollers Exceptions will be spelled out there

Some manufacturers such as Atmel will not give a single value for the maximum current allowed for output pinsInstead they provide a graph that plots the Voh vs Ioh and Vol vs Iol Voh stands for Voltage output high and Vol isVoltage output low As a first approximation Voh is equal to the supply voltage and Vol is zero volts However asthe current increases the voltage drop across the output transistor will increase This results in the voltage being lessthan the supply voltage when the pin is set to a 1 and the output voltage being more than 0 volts when the output isset to a 0

If you try to sink or source large amounts of current the change in the output voltage can cause problems in yourcircuit operations A simple and practical rule of thumb is to find the current when Voh is 90 of the supply voltageand use that as your maximum Ioh Similarly find the current on the chart where Vol is 10 of the supply voltageand use it as the maximum Iol This will keep you out of trouble in most situations

It should be noted that some microcontrollers have a few IO pins that are open collector These donrsquot have the upper(red) transistor as shown in Figure 3-1 These will need external pull up resistors

SummaryA microcontroller IO pin can be set by the program to operate as an output The output voltage will be close to thesupply voltage when the output is set to a logical 1 The output voltage will be close to 0 volts when the pin is set to alogical 0

An output pin can either source or sink the current to or from a load It is important not to exceed the maximum currentratings which can be found in the microcontrollerrsquos data sheet

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Split Core Current Sensor wwwopensourcemetercom

Low Cost Current Transformers Get help specifyingyour solution

Dynamometer Crane Scales wwwcscforcecom

Safe for Overhead Use-High Accuracy Dial DigitalNew Used Rentals

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Dc dc converter design wwwcdiwebcomminmax

ACDC Power Modules Low Cost Great DeliveryStandard and Custom

Custom Pins - Free Quote wwwqualitylapelpinscom

Highest Quality at the Lowest Price Custom Pins aslow as $049 each

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin Thereis a maximum of 200ma total for the package About 25ma should be reserved for the internal operation of theATMega328 leaving about 175ma maximum current forthe rest of the IO pins

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 2Microcontroller Interfacing Part 4

Back to Electronics Main PageHome

Unified Microsystems for electronicequipment modules and kits forengineers electronic hobbyists andAmateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Lecroy Used OscilloscopesOrder securely 247 at TechRecovery InstockFully GuaranteedwwwTechRecoverycom

Digital OscilloscopesDigital Oscilloscopes now from RohdeampSchwarzGet Details Herewwwscope-of-the-artcomRTO

Habey USA BIS-6622Ultra-Conpact Fanless PCs Tunnel Creek IntelAtom E6xx serieswwwhabeyusacom

Custom Force TransducersDesign and manufacturing expertise Contact ustodaywwwhitecorpcomcustom-transducers

>

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 4Driving LED and Other Simple Loads

GoalsThis section describes how to drive an LED and other simple low current loads with a microcontroller output pin

LEDs are very commonly used as indicators on embedded systems When bringing up a new design getting theLED to flash is usually the first step in checking out the hardware When a new programmer writes his first programon a PC it is usually the famous ldquoHello worldrdquo program The embedded system equivalent is a flashing LED

LED characteristicsLEDs are diodes Diodes conduct current when they are forward biased LEDs giveoff light when a current flows through them The amount of light given off or itsbrightness will be proportional to the current The more current that is allowed to flowthe brighter it will get This will continue until you get one bright flash after which it nolonger emits light or acts as a diode for that matter

The data sheet for the LED will generally give the light output at some typical operatingcurrent You can operate the LED at a lower current and get less light or at a highercurrent and get more light as long as you donrsquot exceed the maximum ratings of theLED

Different LEDs will produce different amounts of lights for the same current Highefficiency LEDs will be brighter but will be more expensive than garden variety LEDs Small LEDs typically run at 15 to 25 ma while larger high output types may run100ma or more

Another important characteristic of an LED is the Vfwd or forward drop voltage Adiode has an exponential V-I curve As the current through the LED increases thevoltage drop across it will increase only slightly Vfwd will be listed at a specific currentusually the same one used for rating the light output

Vfwd will usually be around 2 volts for red LEDs and increase with different colorsBlue or white LEDs are often a bit over 3 volts Vfwd will be important for setting theproper current level for the LED

LED design exampleYour project will control a motor It will use an LED to indicate an over temperaturecondition A second identical LED will indicate an over speed condition You select ared LED and look up the specs in the data sheet The luminosity (light output) is whatyou want at the recommended current of 15 ma The voltage drop at that current is 19volts

Figure 4-1 shows the two LEDs being driven in different ways LED1 is uses themicrocontroller output pin P0 as a sink and LED2 uses the pin P1 as a source Youwill note a resistor in series with the LEDs If you were to omit the resistor and drovethe LED directly with the microcontroller pin excessive current would flow when youturned on the LED probably burning out that pin on the microcontroller or maybe the

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

PCB Load CellsStrain guage LoadCells LifetimeWarranty Pluswwwpcbloadtorquecom

Custom ForceTransducersDesign andmanufacturingexpertise Contact ustodaywwwhitecorpcomcustom-hellip

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

LED The question is what value should we use for the resistor

We will use the LED1-R1 combination to do thecalculation The source voltage is 5V from our supplyThe voltage dropped across the LED is 19 which wefound in the data sheet Since the voltage around thecircuit loop must be zero volts

Vdd = Vr + Vfwd

Rearranging the terms gives us

Vr = Vdd ndash Vfwd = 5 ndash 19 = 31 V

We now know the voltage across the resistor is 31Vand we decided earlier that we wanted to drive the LEDat 15ma so a simple application of Ohmrsquos Law will tell uswhat value resistor is needed

R = VI = 31015 = 207 ohms

Resistors come in standard values The closest 5resistor values are 200 ohm and 220 ohm Either wouldbe OK The 200 ohm would result in a little more than15ma of current and the 220 ohm resistor would be lessthan 15ma

The value for R2 is the same as R1 The only realdifference is the microcontroller is supplying 5 voltsinstead of directly getting it from the power supply

Sink or SourceWhich one should you use In most cases it is a matterof personal preference To turn on LED 1 you need toset the PO register bit to a zero To turn on LED2 youset P1 to a logical 1 To many developers setting a pinto a 1 or high seems more natural for turning somethingon so you might want to use the microcontroller pin as asource

One case you might need to use one driving methodover another is when the maximum source and sinkcurrents are not the same and only one method will beable to handle the current needed

If the pin you selected is an open drain type you willneed to sink the current Open drain outputs do not havean internal transistor to Vdd so the pin canrsquot supplycurrent Some microcontrollers have a few IO pins thatare open drain

SummaryControlling an LED with a microcontroller is a commonapplication and is easy to implement Make sure thatcurrent limits of the microcontroller and LED are notexceeded

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

Electronic LEDSigns30 years of LEDexperience offeringcustom LED SignsolutionswwwDataDisplayUsacom

Led display drivericPink is the New GreenZMDI ProductsAvailable at CDIwwwcdiwebcomzmdi

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Super Bright LEDsLarge Selection ofRigid Flexible AndRGB LED Light BarsBuy OnlinesuperbrightledscomRigidLhellip

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

High voltage dc dcACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Paver Lights fromGermanyUL listed IP68 drive-over LED A newstandard for ingroundlightswwwjobe-lightingcom

Enclosure LEDLightingManufactured in NorthAmerica ExplosionProof Low Profilewwwnemaluxcom

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Figure 4-1

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Microcontroller Kits wwwATRIATechnologiescom

8 32 bit LCD USB Order NOW Starting At $79 -Shop On Line

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulation

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 6: Micro Controller Interfacing

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 3Microcontroller Digital Output Basics

GoalThis section goes over the basics of microcontroller output ports It will cover how they can be used to interface to theoutside world and some of the limitations A separate section will cover use of microcontroller IO pins as inputs

Digital IO PortsMicrocontrollers generally combine their output pins into 8 bit ports Op code instructions allow easy manipulations ofthe values as a byte Byte operations are convenient when all 8 bits are part of a data byte At other times you willwant use each bit for a different specific purpose You might want one bit to control an LED a couple more to controlrelays etc There will be op code instructions that let you manipulate individual bits If you program in C Basic orother high level language the compiler will have instructions for controlling individual bits

Most IO pins on a microcontroller can be set as digital inputs or outputs You will want to configure them in the desireddirection early in the software that is executed when the microcontroller is powered up or reset There will be specialregisters for this purpose

The individual pins of an output port can have one of twooutput voltages depending on how the bit is set in the portrsquosoutput register If the bit is set to a ldquo1rdquo the output pin willhave a high voltage The value of the voltage will usuallybe the same as the microcontrollerrsquos supply voltageSometimes setting a bit to a 1 is also called setting it highor just setting the bit Depending on the system design thiswill usually be 33V or 5V Some new microcontrollerdesigned for low power battery applications run at lowervoltages

If the output pin is set to a ldquo0rdquo the voltage at the pin will beclose to zero volts This is also called clearing the bit orsetting it low

The different voltages are obtained by internal transistorsthat switch the output pin to the supply voltage or groundFigure 3-1 is a simplified diagram of an output pinarbitrarily labeled P0 for this example

The red transistor will be on when the output is set to alogical lsquo1rsquo Output pin P0 will be connected to +5V in thisexample If the output is set to a logical lsquo0rsquo the bluetransistor will be on connecting the output pin to ground or0V Only one of the two transistors can be on at a time Both transistors will be off if the pin is configured as aninput and in some other special conditions but one of thetwo will be on if the pin is configured as an output

Driving LoadsAn output pin not connected to anything is not of much

Figure 3-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

interest To do something useful it must be connected toanother device referred here simply as a ldquoloadrdquo A realworld load could be an LED a lamp a transistor or someother circuit element

Generally there are two ways to connect an output pin to aload The first is where the microcontroller supplies thecurrent to drive the device The microcontroller is referredto as the source Current flows from the microcontrollerpower to the output pin through the load and to groundThis configuration is shown in Figure 3-2a

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

The microcontroller pin can also ldquosinkrdquo the current asshown in Figure 3-2b Here the current flows fromthe power supply through the load and through theoutput pin to ground It is important that the load beconnected to the same power supply line as themicrocontroller or you can destroy the IC

Output CurrentsMicrocontrollers are somewhat delicate devices andthe IO lines can only carry a relatively small amountof current The current limit will depend on the typeof microcontroller and the specific pin There willusually be a maximum total current the pins of asingle 8 bit port can handle as well as a limit for allof the outputs for the entire microcontrollerExceeding the limits will destroy the microcontroller

To find out what the maximum currents are youneed to look at the data sheet for the microcontrollerPDF formatted data sheets can be downloaded fromthe manufacturer These can be quite large several

Figure 3-2

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Buy Electronic LED Sign wwwMegaSignInccom

Spend Less On Top Quality Long LastingProgrammable LED Order Now

Pro Energy wwwproenergyca

Rental Power Solutions Generators LightsElectrical Dist

Solid State Relays anaconpowercom

Manufacturer of DIN and Panel mount solid staterelay assemblies

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

hundred pages for a fairly complex one Look for asection titled ldquoElectrical Specificationsrdquo or somethingsimilar Usually in the section there will be a tablecalled ldquoAbsolute Maximum Ratingsrdquo or similar Youwill find a table containing a number of specificationsincluding

Characteristic Symbol ValueOutput Source Current

Ioh -25ma

Output Sink Current Iol 25ma

Ioh stands for Current (I) output high Iol stands for current output low Currents are traditionally referenced as goinginto a pin If the output is high the current flows out so it is given a negative number In some microcontrollers themaximum sink and source current limits for a given pin might be different You will also want to check the portion ofthe data sheet that covers the port you are using Some ports have more drive capacity than others on somemicrocontrollers Exceptions will be spelled out there

Some manufacturers such as Atmel will not give a single value for the maximum current allowed for output pinsInstead they provide a graph that plots the Voh vs Ioh and Vol vs Iol Voh stands for Voltage output high and Vol isVoltage output low As a first approximation Voh is equal to the supply voltage and Vol is zero volts However asthe current increases the voltage drop across the output transistor will increase This results in the voltage being lessthan the supply voltage when the pin is set to a 1 and the output voltage being more than 0 volts when the output isset to a 0

If you try to sink or source large amounts of current the change in the output voltage can cause problems in yourcircuit operations A simple and practical rule of thumb is to find the current when Voh is 90 of the supply voltageand use that as your maximum Ioh Similarly find the current on the chart where Vol is 10 of the supply voltageand use it as the maximum Iol This will keep you out of trouble in most situations

It should be noted that some microcontrollers have a few IO pins that are open collector These donrsquot have the upper(red) transistor as shown in Figure 3-1 These will need external pull up resistors

SummaryA microcontroller IO pin can be set by the program to operate as an output The output voltage will be close to thesupply voltage when the output is set to a logical 1 The output voltage will be close to 0 volts when the pin is set to alogical 0

An output pin can either source or sink the current to or from a load It is important not to exceed the maximum currentratings which can be found in the microcontrollerrsquos data sheet

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Split Core Current Sensor wwwopensourcemetercom

Low Cost Current Transformers Get help specifyingyour solution

Dynamometer Crane Scales wwwcscforcecom

Safe for Overhead Use-High Accuracy Dial DigitalNew Used Rentals

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Dc dc converter design wwwcdiwebcomminmax

ACDC Power Modules Low Cost Great DeliveryStandard and Custom

Custom Pins - Free Quote wwwqualitylapelpinscom

Highest Quality at the Lowest Price Custom Pins aslow as $049 each

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin Thereis a maximum of 200ma total for the package About 25ma should be reserved for the internal operation of theATMega328 leaving about 175ma maximum current forthe rest of the IO pins

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 2Microcontroller Interfacing Part 4

Back to Electronics Main PageHome

Unified Microsystems for electronicequipment modules and kits forengineers electronic hobbyists andAmateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Lecroy Used OscilloscopesOrder securely 247 at TechRecovery InstockFully GuaranteedwwwTechRecoverycom

Digital OscilloscopesDigital Oscilloscopes now from RohdeampSchwarzGet Details Herewwwscope-of-the-artcomRTO

Habey USA BIS-6622Ultra-Conpact Fanless PCs Tunnel Creek IntelAtom E6xx serieswwwhabeyusacom

Custom Force TransducersDesign and manufacturing expertise Contact ustodaywwwhitecorpcomcustom-transducers

>

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 4Driving LED and Other Simple Loads

GoalsThis section describes how to drive an LED and other simple low current loads with a microcontroller output pin

LEDs are very commonly used as indicators on embedded systems When bringing up a new design getting theLED to flash is usually the first step in checking out the hardware When a new programmer writes his first programon a PC it is usually the famous ldquoHello worldrdquo program The embedded system equivalent is a flashing LED

LED characteristicsLEDs are diodes Diodes conduct current when they are forward biased LEDs giveoff light when a current flows through them The amount of light given off or itsbrightness will be proportional to the current The more current that is allowed to flowthe brighter it will get This will continue until you get one bright flash after which it nolonger emits light or acts as a diode for that matter

The data sheet for the LED will generally give the light output at some typical operatingcurrent You can operate the LED at a lower current and get less light or at a highercurrent and get more light as long as you donrsquot exceed the maximum ratings of theLED

Different LEDs will produce different amounts of lights for the same current Highefficiency LEDs will be brighter but will be more expensive than garden variety LEDs Small LEDs typically run at 15 to 25 ma while larger high output types may run100ma or more

Another important characteristic of an LED is the Vfwd or forward drop voltage Adiode has an exponential V-I curve As the current through the LED increases thevoltage drop across it will increase only slightly Vfwd will be listed at a specific currentusually the same one used for rating the light output

Vfwd will usually be around 2 volts for red LEDs and increase with different colorsBlue or white LEDs are often a bit over 3 volts Vfwd will be important for setting theproper current level for the LED

LED design exampleYour project will control a motor It will use an LED to indicate an over temperaturecondition A second identical LED will indicate an over speed condition You select ared LED and look up the specs in the data sheet The luminosity (light output) is whatyou want at the recommended current of 15 ma The voltage drop at that current is 19volts

Figure 4-1 shows the two LEDs being driven in different ways LED1 is uses themicrocontroller output pin P0 as a sink and LED2 uses the pin P1 as a source Youwill note a resistor in series with the LEDs If you were to omit the resistor and drovethe LED directly with the microcontroller pin excessive current would flow when youturned on the LED probably burning out that pin on the microcontroller or maybe the

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

PCB Load CellsStrain guage LoadCells LifetimeWarranty Pluswwwpcbloadtorquecom

Custom ForceTransducersDesign andmanufacturingexpertise Contact ustodaywwwhitecorpcomcustom-hellip

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

LED The question is what value should we use for the resistor

We will use the LED1-R1 combination to do thecalculation The source voltage is 5V from our supplyThe voltage dropped across the LED is 19 which wefound in the data sheet Since the voltage around thecircuit loop must be zero volts

Vdd = Vr + Vfwd

Rearranging the terms gives us

Vr = Vdd ndash Vfwd = 5 ndash 19 = 31 V

We now know the voltage across the resistor is 31Vand we decided earlier that we wanted to drive the LEDat 15ma so a simple application of Ohmrsquos Law will tell uswhat value resistor is needed

R = VI = 31015 = 207 ohms

Resistors come in standard values The closest 5resistor values are 200 ohm and 220 ohm Either wouldbe OK The 200 ohm would result in a little more than15ma of current and the 220 ohm resistor would be lessthan 15ma

The value for R2 is the same as R1 The only realdifference is the microcontroller is supplying 5 voltsinstead of directly getting it from the power supply

Sink or SourceWhich one should you use In most cases it is a matterof personal preference To turn on LED 1 you need toset the PO register bit to a zero To turn on LED2 youset P1 to a logical 1 To many developers setting a pinto a 1 or high seems more natural for turning somethingon so you might want to use the microcontroller pin as asource

One case you might need to use one driving methodover another is when the maximum source and sinkcurrents are not the same and only one method will beable to handle the current needed

If the pin you selected is an open drain type you willneed to sink the current Open drain outputs do not havean internal transistor to Vdd so the pin canrsquot supplycurrent Some microcontrollers have a few IO pins thatare open drain

SummaryControlling an LED with a microcontroller is a commonapplication and is easy to implement Make sure thatcurrent limits of the microcontroller and LED are notexceeded

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

Electronic LEDSigns30 years of LEDexperience offeringcustom LED SignsolutionswwwDataDisplayUsacom

Led display drivericPink is the New GreenZMDI ProductsAvailable at CDIwwwcdiwebcomzmdi

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Super Bright LEDsLarge Selection ofRigid Flexible AndRGB LED Light BarsBuy OnlinesuperbrightledscomRigidLhellip

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

High voltage dc dcACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Paver Lights fromGermanyUL listed IP68 drive-over LED A newstandard for ingroundlightswwwjobe-lightingcom

Enclosure LEDLightingManufactured in NorthAmerica ExplosionProof Low Profilewwwnemaluxcom

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Figure 4-1

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Microcontroller Kits wwwATRIATechnologiescom

8 32 bit LCD USB Order NOW Starting At $79 -Shop On Line

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulation

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 7: Micro Controller Interfacing

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

interest To do something useful it must be connected toanother device referred here simply as a ldquoloadrdquo A realworld load could be an LED a lamp a transistor or someother circuit element

Generally there are two ways to connect an output pin to aload The first is where the microcontroller supplies thecurrent to drive the device The microcontroller is referredto as the source Current flows from the microcontrollerpower to the output pin through the load and to groundThis configuration is shown in Figure 3-2a

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

The microcontroller pin can also ldquosinkrdquo the current asshown in Figure 3-2b Here the current flows fromthe power supply through the load and through theoutput pin to ground It is important that the load beconnected to the same power supply line as themicrocontroller or you can destroy the IC

Output CurrentsMicrocontrollers are somewhat delicate devices andthe IO lines can only carry a relatively small amountof current The current limit will depend on the typeof microcontroller and the specific pin There willusually be a maximum total current the pins of asingle 8 bit port can handle as well as a limit for allof the outputs for the entire microcontrollerExceeding the limits will destroy the microcontroller

To find out what the maximum currents are youneed to look at the data sheet for the microcontrollerPDF formatted data sheets can be downloaded fromthe manufacturer These can be quite large several

Figure 3-2

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

PCB Load Cells wwwpcbloadtorquecom

Strain guage Load Cells Lifetime Warranty Plus

Buy Electronic LED Sign wwwMegaSignInccom

Spend Less On Top Quality Long LastingProgrammable LED Order Now

Pro Energy wwwproenergyca

Rental Power Solutions Generators LightsElectrical Dist

Solid State Relays anaconpowercom

Manufacturer of DIN and Panel mount solid staterelay assemblies

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

hundred pages for a fairly complex one Look for asection titled ldquoElectrical Specificationsrdquo or somethingsimilar Usually in the section there will be a tablecalled ldquoAbsolute Maximum Ratingsrdquo or similar Youwill find a table containing a number of specificationsincluding

Characteristic Symbol ValueOutput Source Current

Ioh -25ma

Output Sink Current Iol 25ma

Ioh stands for Current (I) output high Iol stands for current output low Currents are traditionally referenced as goinginto a pin If the output is high the current flows out so it is given a negative number In some microcontrollers themaximum sink and source current limits for a given pin might be different You will also want to check the portion ofthe data sheet that covers the port you are using Some ports have more drive capacity than others on somemicrocontrollers Exceptions will be spelled out there

Some manufacturers such as Atmel will not give a single value for the maximum current allowed for output pinsInstead they provide a graph that plots the Voh vs Ioh and Vol vs Iol Voh stands for Voltage output high and Vol isVoltage output low As a first approximation Voh is equal to the supply voltage and Vol is zero volts However asthe current increases the voltage drop across the output transistor will increase This results in the voltage being lessthan the supply voltage when the pin is set to a 1 and the output voltage being more than 0 volts when the output isset to a 0

If you try to sink or source large amounts of current the change in the output voltage can cause problems in yourcircuit operations A simple and practical rule of thumb is to find the current when Voh is 90 of the supply voltageand use that as your maximum Ioh Similarly find the current on the chart where Vol is 10 of the supply voltageand use it as the maximum Iol This will keep you out of trouble in most situations

It should be noted that some microcontrollers have a few IO pins that are open collector These donrsquot have the upper(red) transistor as shown in Figure 3-1 These will need external pull up resistors

SummaryA microcontroller IO pin can be set by the program to operate as an output The output voltage will be close to thesupply voltage when the output is set to a logical 1 The output voltage will be close to 0 volts when the pin is set to alogical 0

An output pin can either source or sink the current to or from a load It is important not to exceed the maximum currentratings which can be found in the microcontrollerrsquos data sheet

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Split Core Current Sensor wwwopensourcemetercom

Low Cost Current Transformers Get help specifyingyour solution

Dynamometer Crane Scales wwwcscforcecom

Safe for Overhead Use-High Accuracy Dial DigitalNew Used Rentals

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Dc dc converter design wwwcdiwebcomminmax

ACDC Power Modules Low Cost Great DeliveryStandard and Custom

Custom Pins - Free Quote wwwqualitylapelpinscom

Highest Quality at the Lowest Price Custom Pins aslow as $049 each

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin Thereis a maximum of 200ma total for the package About 25ma should be reserved for the internal operation of theATMega328 leaving about 175ma maximum current forthe rest of the IO pins

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 2Microcontroller Interfacing Part 4

Back to Electronics Main PageHome

Unified Microsystems for electronicequipment modules and kits forengineers electronic hobbyists andAmateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Lecroy Used OscilloscopesOrder securely 247 at TechRecovery InstockFully GuaranteedwwwTechRecoverycom

Digital OscilloscopesDigital Oscilloscopes now from RohdeampSchwarzGet Details Herewwwscope-of-the-artcomRTO

Habey USA BIS-6622Ultra-Conpact Fanless PCs Tunnel Creek IntelAtom E6xx serieswwwhabeyusacom

Custom Force TransducersDesign and manufacturing expertise Contact ustodaywwwhitecorpcomcustom-transducers

>

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 4Driving LED and Other Simple Loads

GoalsThis section describes how to drive an LED and other simple low current loads with a microcontroller output pin

LEDs are very commonly used as indicators on embedded systems When bringing up a new design getting theLED to flash is usually the first step in checking out the hardware When a new programmer writes his first programon a PC it is usually the famous ldquoHello worldrdquo program The embedded system equivalent is a flashing LED

LED characteristicsLEDs are diodes Diodes conduct current when they are forward biased LEDs giveoff light when a current flows through them The amount of light given off or itsbrightness will be proportional to the current The more current that is allowed to flowthe brighter it will get This will continue until you get one bright flash after which it nolonger emits light or acts as a diode for that matter

The data sheet for the LED will generally give the light output at some typical operatingcurrent You can operate the LED at a lower current and get less light or at a highercurrent and get more light as long as you donrsquot exceed the maximum ratings of theLED

Different LEDs will produce different amounts of lights for the same current Highefficiency LEDs will be brighter but will be more expensive than garden variety LEDs Small LEDs typically run at 15 to 25 ma while larger high output types may run100ma or more

Another important characteristic of an LED is the Vfwd or forward drop voltage Adiode has an exponential V-I curve As the current through the LED increases thevoltage drop across it will increase only slightly Vfwd will be listed at a specific currentusually the same one used for rating the light output

Vfwd will usually be around 2 volts for red LEDs and increase with different colorsBlue or white LEDs are often a bit over 3 volts Vfwd will be important for setting theproper current level for the LED

LED design exampleYour project will control a motor It will use an LED to indicate an over temperaturecondition A second identical LED will indicate an over speed condition You select ared LED and look up the specs in the data sheet The luminosity (light output) is whatyou want at the recommended current of 15 ma The voltage drop at that current is 19volts

Figure 4-1 shows the two LEDs being driven in different ways LED1 is uses themicrocontroller output pin P0 as a sink and LED2 uses the pin P1 as a source Youwill note a resistor in series with the LEDs If you were to omit the resistor and drovethe LED directly with the microcontroller pin excessive current would flow when youturned on the LED probably burning out that pin on the microcontroller or maybe the

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

PCB Load CellsStrain guage LoadCells LifetimeWarranty Pluswwwpcbloadtorquecom

Custom ForceTransducersDesign andmanufacturingexpertise Contact ustodaywwwhitecorpcomcustom-hellip

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

LED The question is what value should we use for the resistor

We will use the LED1-R1 combination to do thecalculation The source voltage is 5V from our supplyThe voltage dropped across the LED is 19 which wefound in the data sheet Since the voltage around thecircuit loop must be zero volts

Vdd = Vr + Vfwd

Rearranging the terms gives us

Vr = Vdd ndash Vfwd = 5 ndash 19 = 31 V

We now know the voltage across the resistor is 31Vand we decided earlier that we wanted to drive the LEDat 15ma so a simple application of Ohmrsquos Law will tell uswhat value resistor is needed

R = VI = 31015 = 207 ohms

Resistors come in standard values The closest 5resistor values are 200 ohm and 220 ohm Either wouldbe OK The 200 ohm would result in a little more than15ma of current and the 220 ohm resistor would be lessthan 15ma

The value for R2 is the same as R1 The only realdifference is the microcontroller is supplying 5 voltsinstead of directly getting it from the power supply

Sink or SourceWhich one should you use In most cases it is a matterof personal preference To turn on LED 1 you need toset the PO register bit to a zero To turn on LED2 youset P1 to a logical 1 To many developers setting a pinto a 1 or high seems more natural for turning somethingon so you might want to use the microcontroller pin as asource

One case you might need to use one driving methodover another is when the maximum source and sinkcurrents are not the same and only one method will beable to handle the current needed

If the pin you selected is an open drain type you willneed to sink the current Open drain outputs do not havean internal transistor to Vdd so the pin canrsquot supplycurrent Some microcontrollers have a few IO pins thatare open drain

SummaryControlling an LED with a microcontroller is a commonapplication and is easy to implement Make sure thatcurrent limits of the microcontroller and LED are notexceeded

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

Electronic LEDSigns30 years of LEDexperience offeringcustom LED SignsolutionswwwDataDisplayUsacom

Led display drivericPink is the New GreenZMDI ProductsAvailable at CDIwwwcdiwebcomzmdi

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Super Bright LEDsLarge Selection ofRigid Flexible AndRGB LED Light BarsBuy OnlinesuperbrightledscomRigidLhellip

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

High voltage dc dcACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Paver Lights fromGermanyUL listed IP68 drive-over LED A newstandard for ingroundlightswwwjobe-lightingcom

Enclosure LEDLightingManufactured in NorthAmerica ExplosionProof Low Profilewwwnemaluxcom

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Figure 4-1

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Microcontroller Kits wwwATRIATechnologiescom

8 32 bit LCD USB Order NOW Starting At $79 -Shop On Line

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulation

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 8: Micro Controller Interfacing

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

hundred pages for a fairly complex one Look for asection titled ldquoElectrical Specificationsrdquo or somethingsimilar Usually in the section there will be a tablecalled ldquoAbsolute Maximum Ratingsrdquo or similar Youwill find a table containing a number of specificationsincluding

Characteristic Symbol ValueOutput Source Current

Ioh -25ma

Output Sink Current Iol 25ma

Ioh stands for Current (I) output high Iol stands for current output low Currents are traditionally referenced as goinginto a pin If the output is high the current flows out so it is given a negative number In some microcontrollers themaximum sink and source current limits for a given pin might be different You will also want to check the portion ofthe data sheet that covers the port you are using Some ports have more drive capacity than others on somemicrocontrollers Exceptions will be spelled out there

Some manufacturers such as Atmel will not give a single value for the maximum current allowed for output pinsInstead they provide a graph that plots the Voh vs Ioh and Vol vs Iol Voh stands for Voltage output high and Vol isVoltage output low As a first approximation Voh is equal to the supply voltage and Vol is zero volts However asthe current increases the voltage drop across the output transistor will increase This results in the voltage being lessthan the supply voltage when the pin is set to a 1 and the output voltage being more than 0 volts when the output isset to a 0

If you try to sink or source large amounts of current the change in the output voltage can cause problems in yourcircuit operations A simple and practical rule of thumb is to find the current when Voh is 90 of the supply voltageand use that as your maximum Ioh Similarly find the current on the chart where Vol is 10 of the supply voltageand use it as the maximum Iol This will keep you out of trouble in most situations

It should be noted that some microcontrollers have a few IO pins that are open collector These donrsquot have the upper(red) transistor as shown in Figure 3-1 These will need external pull up resistors

SummaryA microcontroller IO pin can be set by the program to operate as an output The output voltage will be close to thesupply voltage when the output is set to a logical 1 The output voltage will be close to 0 volts when the pin is set to alogical 0

An output pin can either source or sink the current to or from a load It is important not to exceed the maximum currentratings which can be found in the microcontrollerrsquos data sheet

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Split Core Current Sensor wwwopensourcemetercom

Low Cost Current Transformers Get help specifyingyour solution

Dynamometer Crane Scales wwwcscforcecom

Safe for Overhead Use-High Accuracy Dial DigitalNew Used Rentals

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Dc dc converter design wwwcdiwebcomminmax

ACDC Power Modules Low Cost Great DeliveryStandard and Custom

Custom Pins - Free Quote wwwqualitylapelpinscom

Highest Quality at the Lowest Price Custom Pins aslow as $049 each

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin Thereis a maximum of 200ma total for the package About 25ma should be reserved for the internal operation of theATMega328 leaving about 175ma maximum current forthe rest of the IO pins

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 2Microcontroller Interfacing Part 4

Back to Electronics Main PageHome

Unified Microsystems for electronicequipment modules and kits forengineers electronic hobbyists andAmateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Lecroy Used OscilloscopesOrder securely 247 at TechRecovery InstockFully GuaranteedwwwTechRecoverycom

Digital OscilloscopesDigital Oscilloscopes now from RohdeampSchwarzGet Details Herewwwscope-of-the-artcomRTO

Habey USA BIS-6622Ultra-Conpact Fanless PCs Tunnel Creek IntelAtom E6xx serieswwwhabeyusacom

Custom Force TransducersDesign and manufacturing expertise Contact ustodaywwwhitecorpcomcustom-transducers

>

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 4Driving LED and Other Simple Loads

GoalsThis section describes how to drive an LED and other simple low current loads with a microcontroller output pin

LEDs are very commonly used as indicators on embedded systems When bringing up a new design getting theLED to flash is usually the first step in checking out the hardware When a new programmer writes his first programon a PC it is usually the famous ldquoHello worldrdquo program The embedded system equivalent is a flashing LED

LED characteristicsLEDs are diodes Diodes conduct current when they are forward biased LEDs giveoff light when a current flows through them The amount of light given off or itsbrightness will be proportional to the current The more current that is allowed to flowthe brighter it will get This will continue until you get one bright flash after which it nolonger emits light or acts as a diode for that matter

The data sheet for the LED will generally give the light output at some typical operatingcurrent You can operate the LED at a lower current and get less light or at a highercurrent and get more light as long as you donrsquot exceed the maximum ratings of theLED

Different LEDs will produce different amounts of lights for the same current Highefficiency LEDs will be brighter but will be more expensive than garden variety LEDs Small LEDs typically run at 15 to 25 ma while larger high output types may run100ma or more

Another important characteristic of an LED is the Vfwd or forward drop voltage Adiode has an exponential V-I curve As the current through the LED increases thevoltage drop across it will increase only slightly Vfwd will be listed at a specific currentusually the same one used for rating the light output

Vfwd will usually be around 2 volts for red LEDs and increase with different colorsBlue or white LEDs are often a bit over 3 volts Vfwd will be important for setting theproper current level for the LED

LED design exampleYour project will control a motor It will use an LED to indicate an over temperaturecondition A second identical LED will indicate an over speed condition You select ared LED and look up the specs in the data sheet The luminosity (light output) is whatyou want at the recommended current of 15 ma The voltage drop at that current is 19volts

Figure 4-1 shows the two LEDs being driven in different ways LED1 is uses themicrocontroller output pin P0 as a sink and LED2 uses the pin P1 as a source Youwill note a resistor in series with the LEDs If you were to omit the resistor and drovethe LED directly with the microcontroller pin excessive current would flow when youturned on the LED probably burning out that pin on the microcontroller or maybe the

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

PCB Load CellsStrain guage LoadCells LifetimeWarranty Pluswwwpcbloadtorquecom

Custom ForceTransducersDesign andmanufacturingexpertise Contact ustodaywwwhitecorpcomcustom-hellip

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

LED The question is what value should we use for the resistor

We will use the LED1-R1 combination to do thecalculation The source voltage is 5V from our supplyThe voltage dropped across the LED is 19 which wefound in the data sheet Since the voltage around thecircuit loop must be zero volts

Vdd = Vr + Vfwd

Rearranging the terms gives us

Vr = Vdd ndash Vfwd = 5 ndash 19 = 31 V

We now know the voltage across the resistor is 31Vand we decided earlier that we wanted to drive the LEDat 15ma so a simple application of Ohmrsquos Law will tell uswhat value resistor is needed

R = VI = 31015 = 207 ohms

Resistors come in standard values The closest 5resistor values are 200 ohm and 220 ohm Either wouldbe OK The 200 ohm would result in a little more than15ma of current and the 220 ohm resistor would be lessthan 15ma

The value for R2 is the same as R1 The only realdifference is the microcontroller is supplying 5 voltsinstead of directly getting it from the power supply

Sink or SourceWhich one should you use In most cases it is a matterof personal preference To turn on LED 1 you need toset the PO register bit to a zero To turn on LED2 youset P1 to a logical 1 To many developers setting a pinto a 1 or high seems more natural for turning somethingon so you might want to use the microcontroller pin as asource

One case you might need to use one driving methodover another is when the maximum source and sinkcurrents are not the same and only one method will beable to handle the current needed

If the pin you selected is an open drain type you willneed to sink the current Open drain outputs do not havean internal transistor to Vdd so the pin canrsquot supplycurrent Some microcontrollers have a few IO pins thatare open drain

SummaryControlling an LED with a microcontroller is a commonapplication and is easy to implement Make sure thatcurrent limits of the microcontroller and LED are notexceeded

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

Electronic LEDSigns30 years of LEDexperience offeringcustom LED SignsolutionswwwDataDisplayUsacom

Led display drivericPink is the New GreenZMDI ProductsAvailable at CDIwwwcdiwebcomzmdi

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Super Bright LEDsLarge Selection ofRigid Flexible AndRGB LED Light BarsBuy OnlinesuperbrightledscomRigidLhellip

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

High voltage dc dcACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Paver Lights fromGermanyUL listed IP68 drive-over LED A newstandard for ingroundlightswwwjobe-lightingcom

Enclosure LEDLightingManufactured in NorthAmerica ExplosionProof Low Profilewwwnemaluxcom

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Figure 4-1

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Microcontroller Kits wwwATRIATechnologiescom

8 32 bit LCD USB Order NOW Starting At $79 -Shop On Line

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulation

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 9: Micro Controller Interfacing

Microcontroller Digital Output Basics

httpwwww9xtcompage_microdesign_pt3_ouput_basicshtml[27062011 13422 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin Thereis a maximum of 200ma total for the package About 25ma should be reserved for the internal operation of theATMega328 leaving about 175ma maximum current forthe rest of the IO pins

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 2Microcontroller Interfacing Part 4

Back to Electronics Main PageHome

Unified Microsystems for electronicequipment modules and kits forengineers electronic hobbyists andAmateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Lecroy Used OscilloscopesOrder securely 247 at TechRecovery InstockFully GuaranteedwwwTechRecoverycom

Digital OscilloscopesDigital Oscilloscopes now from RohdeampSchwarzGet Details Herewwwscope-of-the-artcomRTO

Habey USA BIS-6622Ultra-Conpact Fanless PCs Tunnel Creek IntelAtom E6xx serieswwwhabeyusacom

Custom Force TransducersDesign and manufacturing expertise Contact ustodaywwwhitecorpcomcustom-transducers

>

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 4Driving LED and Other Simple Loads

GoalsThis section describes how to drive an LED and other simple low current loads with a microcontroller output pin

LEDs are very commonly used as indicators on embedded systems When bringing up a new design getting theLED to flash is usually the first step in checking out the hardware When a new programmer writes his first programon a PC it is usually the famous ldquoHello worldrdquo program The embedded system equivalent is a flashing LED

LED characteristicsLEDs are diodes Diodes conduct current when they are forward biased LEDs giveoff light when a current flows through them The amount of light given off or itsbrightness will be proportional to the current The more current that is allowed to flowthe brighter it will get This will continue until you get one bright flash after which it nolonger emits light or acts as a diode for that matter

The data sheet for the LED will generally give the light output at some typical operatingcurrent You can operate the LED at a lower current and get less light or at a highercurrent and get more light as long as you donrsquot exceed the maximum ratings of theLED

Different LEDs will produce different amounts of lights for the same current Highefficiency LEDs will be brighter but will be more expensive than garden variety LEDs Small LEDs typically run at 15 to 25 ma while larger high output types may run100ma or more

Another important characteristic of an LED is the Vfwd or forward drop voltage Adiode has an exponential V-I curve As the current through the LED increases thevoltage drop across it will increase only slightly Vfwd will be listed at a specific currentusually the same one used for rating the light output

Vfwd will usually be around 2 volts for red LEDs and increase with different colorsBlue or white LEDs are often a bit over 3 volts Vfwd will be important for setting theproper current level for the LED

LED design exampleYour project will control a motor It will use an LED to indicate an over temperaturecondition A second identical LED will indicate an over speed condition You select ared LED and look up the specs in the data sheet The luminosity (light output) is whatyou want at the recommended current of 15 ma The voltage drop at that current is 19volts

Figure 4-1 shows the two LEDs being driven in different ways LED1 is uses themicrocontroller output pin P0 as a sink and LED2 uses the pin P1 as a source Youwill note a resistor in series with the LEDs If you were to omit the resistor and drovethe LED directly with the microcontroller pin excessive current would flow when youturned on the LED probably burning out that pin on the microcontroller or maybe the

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

PCB Load CellsStrain guage LoadCells LifetimeWarranty Pluswwwpcbloadtorquecom

Custom ForceTransducersDesign andmanufacturingexpertise Contact ustodaywwwhitecorpcomcustom-hellip

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

LED The question is what value should we use for the resistor

We will use the LED1-R1 combination to do thecalculation The source voltage is 5V from our supplyThe voltage dropped across the LED is 19 which wefound in the data sheet Since the voltage around thecircuit loop must be zero volts

Vdd = Vr + Vfwd

Rearranging the terms gives us

Vr = Vdd ndash Vfwd = 5 ndash 19 = 31 V

We now know the voltage across the resistor is 31Vand we decided earlier that we wanted to drive the LEDat 15ma so a simple application of Ohmrsquos Law will tell uswhat value resistor is needed

R = VI = 31015 = 207 ohms

Resistors come in standard values The closest 5resistor values are 200 ohm and 220 ohm Either wouldbe OK The 200 ohm would result in a little more than15ma of current and the 220 ohm resistor would be lessthan 15ma

The value for R2 is the same as R1 The only realdifference is the microcontroller is supplying 5 voltsinstead of directly getting it from the power supply

Sink or SourceWhich one should you use In most cases it is a matterof personal preference To turn on LED 1 you need toset the PO register bit to a zero To turn on LED2 youset P1 to a logical 1 To many developers setting a pinto a 1 or high seems more natural for turning somethingon so you might want to use the microcontroller pin as asource

One case you might need to use one driving methodover another is when the maximum source and sinkcurrents are not the same and only one method will beable to handle the current needed

If the pin you selected is an open drain type you willneed to sink the current Open drain outputs do not havean internal transistor to Vdd so the pin canrsquot supplycurrent Some microcontrollers have a few IO pins thatare open drain

SummaryControlling an LED with a microcontroller is a commonapplication and is easy to implement Make sure thatcurrent limits of the microcontroller and LED are notexceeded

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

Electronic LEDSigns30 years of LEDexperience offeringcustom LED SignsolutionswwwDataDisplayUsacom

Led display drivericPink is the New GreenZMDI ProductsAvailable at CDIwwwcdiwebcomzmdi

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Super Bright LEDsLarge Selection ofRigid Flexible AndRGB LED Light BarsBuy OnlinesuperbrightledscomRigidLhellip

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

High voltage dc dcACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Paver Lights fromGermanyUL listed IP68 drive-over LED A newstandard for ingroundlightswwwjobe-lightingcom

Enclosure LEDLightingManufactured in NorthAmerica ExplosionProof Low Profilewwwnemaluxcom

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Figure 4-1

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Microcontroller Kits wwwATRIATechnologiescom

8 32 bit LCD USB Order NOW Starting At $79 -Shop On Line

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulation

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 10: Micro Controller Interfacing

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 4Driving LED and Other Simple Loads

GoalsThis section describes how to drive an LED and other simple low current loads with a microcontroller output pin

LEDs are very commonly used as indicators on embedded systems When bringing up a new design getting theLED to flash is usually the first step in checking out the hardware When a new programmer writes his first programon a PC it is usually the famous ldquoHello worldrdquo program The embedded system equivalent is a flashing LED

LED characteristicsLEDs are diodes Diodes conduct current when they are forward biased LEDs giveoff light when a current flows through them The amount of light given off or itsbrightness will be proportional to the current The more current that is allowed to flowthe brighter it will get This will continue until you get one bright flash after which it nolonger emits light or acts as a diode for that matter

The data sheet for the LED will generally give the light output at some typical operatingcurrent You can operate the LED at a lower current and get less light or at a highercurrent and get more light as long as you donrsquot exceed the maximum ratings of theLED

Different LEDs will produce different amounts of lights for the same current Highefficiency LEDs will be brighter but will be more expensive than garden variety LEDs Small LEDs typically run at 15 to 25 ma while larger high output types may run100ma or more

Another important characteristic of an LED is the Vfwd or forward drop voltage Adiode has an exponential V-I curve As the current through the LED increases thevoltage drop across it will increase only slightly Vfwd will be listed at a specific currentusually the same one used for rating the light output

Vfwd will usually be around 2 volts for red LEDs and increase with different colorsBlue or white LEDs are often a bit over 3 volts Vfwd will be important for setting theproper current level for the LED

LED design exampleYour project will control a motor It will use an LED to indicate an over temperaturecondition A second identical LED will indicate an over speed condition You select ared LED and look up the specs in the data sheet The luminosity (light output) is whatyou want at the recommended current of 15 ma The voltage drop at that current is 19volts

Figure 4-1 shows the two LEDs being driven in different ways LED1 is uses themicrocontroller output pin P0 as a sink and LED2 uses the pin P1 as a source Youwill note a resistor in series with the LEDs If you were to omit the resistor and drovethe LED directly with the microcontroller pin excessive current would flow when youturned on the LED probably burning out that pin on the microcontroller or maybe the

Circuitoscilloscope8 Out of 10 EngineersRely on OurOscilloscopes ComeSee Why Todaywwwtekcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

PCB Load CellsStrain guage LoadCells LifetimeWarranty Pluswwwpcbloadtorquecom

Custom ForceTransducersDesign andmanufacturingexpertise Contact ustodaywwwhitecorpcomcustom-hellip

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

LED The question is what value should we use for the resistor

We will use the LED1-R1 combination to do thecalculation The source voltage is 5V from our supplyThe voltage dropped across the LED is 19 which wefound in the data sheet Since the voltage around thecircuit loop must be zero volts

Vdd = Vr + Vfwd

Rearranging the terms gives us

Vr = Vdd ndash Vfwd = 5 ndash 19 = 31 V

We now know the voltage across the resistor is 31Vand we decided earlier that we wanted to drive the LEDat 15ma so a simple application of Ohmrsquos Law will tell uswhat value resistor is needed

R = VI = 31015 = 207 ohms

Resistors come in standard values The closest 5resistor values are 200 ohm and 220 ohm Either wouldbe OK The 200 ohm would result in a little more than15ma of current and the 220 ohm resistor would be lessthan 15ma

The value for R2 is the same as R1 The only realdifference is the microcontroller is supplying 5 voltsinstead of directly getting it from the power supply

Sink or SourceWhich one should you use In most cases it is a matterof personal preference To turn on LED 1 you need toset the PO register bit to a zero To turn on LED2 youset P1 to a logical 1 To many developers setting a pinto a 1 or high seems more natural for turning somethingon so you might want to use the microcontroller pin as asource

One case you might need to use one driving methodover another is when the maximum source and sinkcurrents are not the same and only one method will beable to handle the current needed

If the pin you selected is an open drain type you willneed to sink the current Open drain outputs do not havean internal transistor to Vdd so the pin canrsquot supplycurrent Some microcontrollers have a few IO pins thatare open drain

SummaryControlling an LED with a microcontroller is a commonapplication and is easy to implement Make sure thatcurrent limits of the microcontroller and LED are notexceeded

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

Electronic LEDSigns30 years of LEDexperience offeringcustom LED SignsolutionswwwDataDisplayUsacom

Led display drivericPink is the New GreenZMDI ProductsAvailable at CDIwwwcdiwebcomzmdi

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Super Bright LEDsLarge Selection ofRigid Flexible AndRGB LED Light BarsBuy OnlinesuperbrightledscomRigidLhellip

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

High voltage dc dcACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Paver Lights fromGermanyUL listed IP68 drive-over LED A newstandard for ingroundlightswwwjobe-lightingcom

Enclosure LEDLightingManufactured in NorthAmerica ExplosionProof Low Profilewwwnemaluxcom

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Figure 4-1

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Microcontroller Kits wwwATRIATechnologiescom

8 32 bit LCD USB Order NOW Starting At $79 -Shop On Line

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulation

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 11: Micro Controller Interfacing

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

LED The question is what value should we use for the resistor

We will use the LED1-R1 combination to do thecalculation The source voltage is 5V from our supplyThe voltage dropped across the LED is 19 which wefound in the data sheet Since the voltage around thecircuit loop must be zero volts

Vdd = Vr + Vfwd

Rearranging the terms gives us

Vr = Vdd ndash Vfwd = 5 ndash 19 = 31 V

We now know the voltage across the resistor is 31Vand we decided earlier that we wanted to drive the LEDat 15ma so a simple application of Ohmrsquos Law will tell uswhat value resistor is needed

R = VI = 31015 = 207 ohms

Resistors come in standard values The closest 5resistor values are 200 ohm and 220 ohm Either wouldbe OK The 200 ohm would result in a little more than15ma of current and the 220 ohm resistor would be lessthan 15ma

The value for R2 is the same as R1 The only realdifference is the microcontroller is supplying 5 voltsinstead of directly getting it from the power supply

Sink or SourceWhich one should you use In most cases it is a matterof personal preference To turn on LED 1 you need toset the PO register bit to a zero To turn on LED2 youset P1 to a logical 1 To many developers setting a pinto a 1 or high seems more natural for turning somethingon so you might want to use the microcontroller pin as asource

One case you might need to use one driving methodover another is when the maximum source and sinkcurrents are not the same and only one method will beable to handle the current needed

If the pin you selected is an open drain type you willneed to sink the current Open drain outputs do not havean internal transistor to Vdd so the pin canrsquot supplycurrent Some microcontrollers have a few IO pins thatare open drain

SummaryControlling an LED with a microcontroller is a commonapplication and is easy to implement Make sure thatcurrent limits of the microcontroller and LED are notexceeded

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

Electronic LEDSigns30 years of LEDexperience offeringcustom LED SignsolutionswwwDataDisplayUsacom

Led display drivericPink is the New GreenZMDI ProductsAvailable at CDIwwwcdiwebcomzmdi

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Super Bright LEDsLarge Selection ofRigid Flexible AndRGB LED Light BarsBuy OnlinesuperbrightledscomRigidLhellip

BC LED Lights-Direct LEDLED Grow Lights - 3-5WATT- LED UFO-9995 - NEW- 300Watt59995wwwbcledlightscom

High voltage dc dcACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flashing LED STOPSignReduces blow-throughs by 529 ampincomplete stops by28wwwtapconetcomblinkershellip

Paver Lights fromGermanyUL listed IP68 drive-over LED A newstandard for ingroundlightswwwjobe-lightingcom

Enclosure LEDLightingManufactured in NorthAmerica ExplosionProof Low Profilewwwnemaluxcom

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Figure 4-1

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Microcontroller Kits wwwATRIATechnologiescom

8 32 bit LCD USB Order NOW Starting At $79 -Shop On Line

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulation

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 12: Micro Controller Interfacing

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Figure 4-1

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Transformer Services transformerengineeringservicescom

Transformer Substation Maintenance Construction24 hr Emergency Srvs

Microcontroller Kits wwwATRIATechnologiescom

8 32 bit LCD USB Order NOW Starting At $79 -Shop On Line

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulation

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 13: Micro Controller Interfacing

Interfacing an LED to a microcontroller

httpwwww9xtcompage_microdesign_pt4_drive_ledhtml[27062011 13454 PM]

Created with the QTHcom SiteBuilder

Arduino TipsThe IO pins of the ATMega328 used on the ArduinoDuemilanove can sink and source 40 ma per pin There is a maximum of 200ma total for the package About 25 ma should be reserved for the internaloperation of the ATMega328 leaving about 175mamaximum current for the rest of the IO pins

Gotcha Checklist1 Ensure the operating current does not exceedthe LED maximum operating current

2 Ensure the operating current does not exceedthe microcontroller sink or source maximums

3 If using the current sinking configuration use thesame voltage to drive the LED that supplies themicrocontroller

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 3

Microcontroller Interfacing Part 5Back to Electronics Main Page

Home Page

Unified Microsystems for electronic equipmentmodules and kits for engineers electronichobbyists and Amateur Radio operators

copy 2009 - 2011 Gary C Sutcliffe

Learn how

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 14: Micro Controller Interfacing

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 5Microcontroller Digital Input Basics

GoalsThis section describes the basic characteristics of a microcontroller IO pin when it is configured as a digital input

Input PinsMost of a microcontrollerrsquos IO pins can be configured as an output or an input Part 2 described the basics when apin is configured as an output This section describes it when it is configured as an input A special register willcontrol if a pin is an input or output You need your program to set up the port direction registers as an early stepwhen power is applied to the chip or it comes out of reset

IO pins are usually configured in groups of 8 bit IO ports The program can read the port and will get a valuebetween 0 and 255 depending on the states of the input pins In assembly language programming there will usuallybe op code instructions that allow reading a single pin of a port C compilers will usually implement single bitfunctions as well IO functions are not defined in standard KampR C and each compiler handles them a littledifferently Otherwise the programmer will have to read the entire port and mask off the other bits

A pin with a low voltage (ideally 0 volts) willread as a logical 0 A pin with a voltage nearVcc (or Vdd) will read as a logic 1 As a firstapproximation any input less than half of Vccwill read as a 0 and any input over Vcc2 willread as a 1

There is a voltage band however right aroundVcc2 where there is no guarantee what statewill be read Refer to Figure 5-1 This showsthe logic thresholds of a typical microcontrollerThe X axis represents the supply voltage Vcc (Vdd on some data sheets) The Y axisrepresents the voltage on an input pin Theblack dashed line is where the input is 12 Vcc

For a given supply voltage if the input pinvoltage is below the green line the pin will beread as 0 Above the blue line the input willread as 1 Between the green and blue lines isa ldquono manrsquos landrdquo where it might read as a 0 orit might read as a 1 If the signal is near Vcc2a little noise can cause the voltage to jump overto the other side and cause an incorrectreading

Figure 5-1

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

As a general rule you will want the input levels either near 0 volts or thesupply voltage to avoid incorrect readings You will notice that when thesupply voltage is low the range for a 0 or 1 gets very small With a low Vcc a

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 15: Micro Controller Interfacing

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

Precision FoilResistorsRadials from 0005in 7-15 days SMDsfrom 001 in 15dayswwwcharcroftcom

little noise on an input can cause an improper read For applications withnoisy electrical environments it is usually best to run the microcontroller nearthe high end of the allowable Vcc range On the other hand running at highersupply voltages will mean more power consumption Those are the kind oftradeoffs that you will need to make as a circuit designer

The actual levels and slope of the thresholds indicated by the blue and greenlines of Figure 6-1 will depend on the microcontroller in question They willalso change a bit depending on the device temperature Some special pinssuch as the reset pin might have different thresholds than regular IO pins

Referring again to Figure 5-1 the red line shows the input voltage equal tothe supply voltage You donrsquot want to subject inputs to voltages above Vcc oryou can damage the IC For that matter you do not want the input to gobelow ground (0V) That can cause the internal circuitry in the IC to latch upand possibly draw excessive current and damage or destroy the IC

Pull ups and pull downsSometimes you want an input to read as a 1 or 0 as a default Suppose youhave a sensor on a cable that plugs into your device It is possible that theuser will disconnect the cable If the input pin is left floating it mightsometimes read as a 1 sometimes as a 0 Your code might interpret this aschanges from a sensor and not act the way you want

Putting a pull up resistor will set the input voltage near Vcc and it will read asa 1 A pull down resistor will bring the voltage near 0V and it will read as azero Figure 5-2 shows pull up and pull down resistors The switch sensor orother component that generates the normal 1 and 0 voltages must be able toover drive the resistor

What value resistor should you use for these resistors There are no hardand fast rules but there are some guidelines A resistor with a relatively lowresistance is called a strong pull up That is because it takes a lot of currentto pull it down Alternatively a high resistance pull up is a weak pull upbecause it will not take much to pull it down

If your circuit is in an electrically noisy environment some of that will getcoupled into your circuit If a weak pull up is used the noise could bepowerful enough to cause a false reading If you use a strong pull up thenoise risk is reduced but the circuit driving the input must be able to handlethe load and the systemrsquos over all power consumption will be higher Youhave to understand the conditions your circuit will operate in and make theproper compromises

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

TransformerServicesTransformerSubstationMaintenanceConstruction 24 hrEmergency Srvs

Flexible PrintedCircuitsFlexible Printed Circuitamp Other InterconnectSolutions ExpertsMiracoInccom

Digital LED SignBoardAttract CustomersWith ProgrammableDigital LED BoardsContact Us NowwwwMegaSignInccom

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 16: Micro Controller Interfacing

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Some microcontrollers have internal pull ups You set a bit in an internal register to turn themon These are nice because you donrsquot have toadd the pull up resistors in the hardwaredesign saving cost board space and assemblytime The value of internal pull ups is usuallypretty high (weak pull up) and the actual valueoften has a huge range Internal pull ups arehandy but evaluate the parameters in the datasheet before using them

So what values should be used for pull upsand pull downs There are no hard and fastrules but generally anything under a fewthousand ohms is a strong pull up Weak pullups often reach 40-50KΩ I donrsquot like to goover 10KΩ unless I have a specific reason likeneeding to keep power consumption extremelylow

Switching between Input and Output ModeIn some applications you may want a pin to bean input some of the time and an output atother times An example is where themicrocontroller is communicating with anothersystem or IC Sometimes the microcontroller issending data to another IC and at other timesthe IC is sending data to the microcontroller I2C and Two Wire Interfaces are commonexamples where an IO pin is used as both aninput and output

Figure 5-2

Arduino TipsYou can enable the internal pull up resistor on an Arduino pinwith the following instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pullup resistor

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

One thing to keep in mind is that some microcontrollers require one or more clock cycles after a direction changebefore the data on the pin can be trusted Many designers have wasted a lot of time trying to figure out why theirsystem does not work because they overlooked this fact

SummaryMicrocontroller pins can be used as inputs to sense conditions in the outside world Digital IO pins can only detectON or OFF (1 or 0) states A high voltage (near Vcc) will read as a logical 1 and a low voltage (near 0V or Ground)will read as a logical 0

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 17: Micro Controller Interfacing

Microcoontroller Input Pin Basics

httpwwww9xtcompage_microdesign_pt5_input_basicshtml[27062011 13510 PM]

Created with the QTHcom SiteBuilder

Gotcha Checklist1 Ensure signals applied to digital inputs areeither near Vcc or ground

2 Size pull ups and pull downs appropriately

3 Allow time enough time when switching an IOpinrsquos direction Microcontroller Interfacing Table of Contents

Microcontroller Interfacing Part 4

Microcontroller Interfacing Part 6Back to Electronics Main Page

Home

copy 2009 - 2011 Gary C Sutcliffe

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 18: Micro Controller Interfacing

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 6Interfacing Switches

GoalsThis section covers techniques to interface switches to a microcontroller

Controlling Inputs with SwitchesA microcontroller canrsquot make any decisions on controlling something in the outside world without sensing somethingabout it The simplest thing for a microcontroller to check is the status of a switch Is it open or closed

Switches can be used as operator controls They can sense if a door is open or closed A limit switch can detect ifa part of a machine has reached a certain position Switches can be used for many purposes but they can be inonly one of two states On (closed) or Off (open)

Figure 6-1 shows two common ways to interface switches to a microcontroller input Input P0 uses R1 as a pull upIf SW1 is open P0 will be high and read as a logical 1 When SW1 is closed pin P0 is shorted to ground or 0Vand P0 will read as a logical 0

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Honeywell Distributor AlliedEleccomHoneywell

Allied Has the Honeywell Parts You Need OrderToday

5 Pin Modules lea-networkscom

State of the Art Protection Modules CompetitivePricing

Figure 6-1

Make Prototypes In-House wwwlpkfusacom

Prototyping equipment from LPKF Circuit BoardPlotter Plating etc

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Printed Circuit Boards wwwcirexxcom

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 19: Micro Controller Interfacing

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Note that some microcontrollers have internal pull up resistors that can be enabled under program controller Youdonrsquot need to wire up R1 if you use an internal pull up resistor If you use an external pull up resistor tie the high endto the same voltage used to run the microcontroller Using a higher voltage will damage the microcontroller and alower voltage may result the circuit not working Part 5 discussed the use of pull up resistors in more detail

P1 has R2 as a pull down resistor When SW2 is open P1 is pulled low and read as a logical 0 Closing SW2causes current to flow through R2 raising the voltage at P1 to the Vcc level At that point P1 will read as a logical 1

If you donrsquot have a pull up or pull down resistor the input will float and when the switch is open the input will be verysusceptible to noise causing false readings Part 5 discusses this in more detail Which of the two methods shouldyou use I usually use the pull up resistor That is a habit gained when I did a lot of design with bipolar transistor TTLlogic gates Pull down resistors are not recommended with that technology With MOS microcontrollers there is nomajor advantage of one over another Use whatever you prefer

Your program can check the states of the switches and execute different code depending on the state of the switch

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet ExpressAcircreg5 Million Reasonsto See Whats InStock OrderComponentsOnlineAvnetExpressAvnetcom

Electronic FlowSwitch

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Selecting Resistor ValuesWhat value should be used for pull up (or pull down) resistors A lot depends on thedemands of the application A big part of the decision is how much power the applicationcan afford to use

When a switch is closed current will flow through the resistor The current will depend onthe value of the resistor and the voltage used to power the circuit The current can bedetermined with Ohmrsquos Law

I = VRSimilarly the power consumed by using the formula

P= V^2RWith a 1000 (1K) ohm resistor and a 5V supply voltage we get the following

I = VR = 51000 = 005 A or 5 ma P= V^2R = 5 51000 = 025W or 25 mw

With a 10000 (10K) ohm resistor in the same circuit we get

I = VR = 510000 = 0005 A or 5 ma P= V^2R = 5 510000 = 0025W or 25 mw

Clearly using a higher value resistor uses less power so why not just use very largeresistors for switch pull ups The problem is that high resistor values make the circuitmore sensitive to noise A small amount of noise current injected into a high impedancecircuit could generate enough voltage to cause an incorrect reading

Too high a resistance can also make a circuit sensitive to leakage from moisture orcontamination on the circuit board I once designed a portable device with a PICmicrocontroller It had some input switches for operator control Wanting to maximizebattery life I used 47K Ω pull up resistors Things worked fine until units started to getreturned for erratic operation They all worked fine once they got back The ones gettingreturned were coming back from Central America and Pacific islands It turned out thatcondensation from the high humidity was enough of a path to pull the input pins low Afterthat the boards were given a conformal coating to keep moisture off the conductors

The purpose of the switch will also determine how critical power consumption is even in abattery application If the switch is a push button type the user only presses occasionallyfor a fraction of second the total power consumption will be low A slide or toggle switchthat might be left in the closed position for long periods of time could cause significantbattery drain

As a practical matter values greater than 1KΩ and less than 20KΩ will work pretty wellUnless I have some special needs I usually just use 10K resistors as a good compromisebetween power use and noise immunity A future section of this series will cover handling

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 20: Micro Controller Interfacing

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Liquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

Flexible PrintedCircuitsFlexible PrintedCircuit amp OtherInterconnectSolutions ExpertsMiracoInccom

Switch BounceAn unfortunate characteristic of switches is that

DWYERAcircregLevel SwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

5 MillionReasons To BuyAvnet Express -QualityComponentsSame DayShipping OrderOnlineAvnetExpressAvnetcom

Industrial-gradeEthernetManufacturer ofEthernet switchesfor harshindustrialenvironmentswwwmoxacom

DWYERreg LevelSwitchesFull Range ofLevel Sensors forall applicationswwwdwyer-instcom

HoneywellDistributorAllied Has theHoneywell PartsYou Need OrderTodayAlliedEleccomHoneyhellip

Avnet Express1 GlobalDistributor ofElectronicComponents byEE Times-OrderOnlineAvnetExpressAvnetcom

Electronic FlowSwitchLiquids Gasesand SlurriesReliable CostEffective amp InStockwwwameritrolcom

other ways of dealing with noise on input lines

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 21: Micro Controller Interfacing

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

they donrsquot switch cleanly The mechanicalcomponents of a switch vibrate back and forthmaking a number of momentary contacts beforefinally settling down to the final state Figure 6-2shows what an oscilloscope attached to P0 inFigure 6-1 would show when SW1 is closed P0goes high and low a number of times when theswitch is first closed

A microcontroller operates thousands of timesfaster than a mechanical switch It would see eachof the short pulses as individual switch openingsand closures If the switch is used for countingevents the microcontroller count would be manytimes the true number of events In anotherapplication the switch might be used to turn a lightor motor on and off

Figure 6-2

Press the button and the light goes on Press it again and it will go off If switch bounce is not accounted for theuser would think the switch or device is operating erratically When the button is pressed sometimes the light willnot go on other times it will not turn it off when it was supposed to In reality the microcontroller is turning the lighton and off several times but too fast to observe The final number of bounces the switch makes each time willdetermine if desired operation is achieved

There are a number of ways of handling switch bounce Simple cross couple logic gates forming flip-flops can beused but debouncing switches is usually done in software Once developed software is free Hardware costsmoney each time another unit is manufactured Simple C-like pseudo code to debounce a switch is shown in Listing6-1 It could be used with the configuration of P0 in Figure 6-1

Listing 6-1 is a function that the program callsevery time it needs to check the status of a switchattached to IO pin P0 The function returns a bytewith the value of 1 if the switch is closed and avalue of 0 if it is open It is assumed that the portpin has already been set up to act as an input The actual syntax of the statements for readingthe state of a pin will depend on the compiler TheC language standards do not define syntax forhow an input is read so each compilerimplements this differently

The first statement inside the function checks ifthe port is reading low (switch closed) If it is wait50 milliseconds and see if it is still closed If it isstill closed the function returns a value of 1 toindicate the switch is closed If none of theconditions are met the function returns a logical0 indicating the switch is open

The program must call this function frequently toensure it catches every switch closure This isespecially true if the switch closure is going to beshort say for a user press of a momentary pushbutton switch If the delay function is not in thereand the switch has bounce the function could becalled several times and get multiple readings of

char Check_P0(void) returns 1 if switch attached to P0 is closed 0 if switch is open

if(P0 == 0) check if pin P0 is low meaning switch is on

delay_msec(50) wait 50 msec to allow any switch bounce to die out

if(P0 == 0)return(1) the switch is really closed

return(0) the switch is open

end of Check_P0 function

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 22: Micro Controller Interfacing

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

the switch being open and closed The delayprevents the function from being called multipletimes during a debounce period

The delay function in Listing 6-1 sits in a loop untilthe period specified has elapsed Your compilermay have a delay function as part of its libraryfunctions Otherwise you will have to write yourown You will also need to write your own or findone on line if you program in assembly language The listing shows a delay of 50 milliseconds Theactual delay you need will depend on the switchyou are using This is usually doneexperimentally The value of 50 millisecondsworks well for many switches and is a goodstarting point

Listing 6-1

If your delay period is too short you risk reading multiple switch closures from a single actual switch closure If yourperiod is too long you risk missing multiple real short period switch closures Also with simple program delayfunctions you are just in a loop counting milliseconds Unless you have a multitasking application with an appropriatedelay function your program is not doing any other useful things during the delay period Fifty milliseconds is a verylong time to a modern microcontroller This may or may not be important depending on your application

There is one other programming consideration After it detects a switch closure the program needs to verify theswitch is then opened before assuming the value returned by the function is a new switch closure

SummaryThis section covered the basic methods of using a switch to indicate an external event Switched inputs need a pullup or pull down resistor to hold the input to a specific value when the switch is open The value of the resistor willhave an effect on the power consumption of the circuit

Switches do not switch cleanly and some debounce method must be used to prevent multiple false readings

Arduino Tips

You can use the internal pull up resistor when connecting a switch to anArduino pin Connect the other switch pin to ground like SW-1 in Figure 6-1

You can enable the internal pull up resistor on an Arduino pin with thefollowing instructions

pinMode(pin INPUT) set pin to be an input

digitalWrite(pin HIGH) turn on pins pull up resistor

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Avnet Express AcircregAvnet ExpressAcircreg-- We Have5000000 Parts Build YourOwn BOMAvnetExpressAvnetcom

DWYERAcircreg Level SwitchesFull Range of Level Sensorsfor all applicationswwwdwyer-instcom

Honeywell DistributorAllied Has the HoneywellParts You Need Order TodayAlliedEleccomHoneywell

Flexible Printed CircuitsSpecializing in FlexiblePrinted Circuit designs callMiraco todayMiracoInccom

Wireless Dev BoardsZigBee wireless developmentboards for sensor andautomation modulesg-centriccomgstoregstorehtml

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 23: Micro Controller Interfacing

Interfacing switches to microcontrollers

httpwwww9xtcompage_microdesign_pt6_switch_inputshtml[27062011 13528 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 5Microcontroller Interfacing Part 7

Back to Electronics Main PageHome Page

Gotcha Checklist1 Use a pull up or pull down resistor to ensurethe pin state when the switch is open

2 Account for switch debounce to preventdetecting multiple false switch closures (oropens)

copy 2009 - 2011 Gary C Sutcliffe

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 24: Micro Controller Interfacing

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 7Using Transistors to Drive Loads

GoalsMany components such as relays solenoids high power LEDs buzzers and others require more drive currentandor higher voltages than the microcontroller outputs can handle One way around this problem is to use themicrocontroller to drive a transistor which in turn controls the load This section will consider only the NPN typetransistors Other transistor types will be considered in other sections

Transistor BasicsTransistors are current amplifiers A small current is driven through the base and emitter which is essentially adiode This is referred to as Ib The collector current will be the base current multiplied by the transistorrsquos DC gainreferred to as hFE in the data sheets Figure 7-1 shows a simple transistor circuit with the elements of the transistorlabeled

A transistor can be operated in its linear range A boom box radio will have a number of transistorized linearamplifier stages increasing a weak radio signal to a level loud enough to disturb an entire neighborhood

Microcontroller applications usually do not run the transistors in thelinear range Rather they are used as ON-OFF switches Considerthe circuit in Figure 7-1 Assume that when the output pin P0 is sethigh the base current Ib is 10 ma and the transistorrsquos hFE is 100 What will be the collector current

Ic = Ib hFe= 01 100 = 1A

Is that correct No Suppose we shorted out the transistor Whatwould the current be then Ohmrsquos Law tells us

I = VR = 10100 = 1A = 100ma

At some point the external components will force a limit on thecollector current At that point the transistor is in saturation Anyincrease in base current will have no effect on the collector current The transistor is acting as a switch In most microcontroller circuitstransistors are used as switches and are either on or off

A transistor is not a perfect switch Even in saturation there will be avoltage across the transistor between the collector and the emitter This voltage is known as Vce(sat) This will usually range between3V and 1V depending on the voltage and currents In many circuitsVce(sat) can be ignored

Figure 7-1

Example Driving a RelayFigure 7-2 shows a typical circuit where a transistor is used to drive a relay A relay can be used to switch highervoltages and currents than the microcontroller can It can also be used to switch AC signals Looking through acatalog we select a 12V relay The data sheet says the coil resistance is 360Ω What will the current through thecoil be Ohmrsquos Law says

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 25: Micro Controller Interfacing

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

I = VR = 12360 = 033A or 33ma

We cannot drive this relay with the microcontroller output pin directly for two reasons First the relay must use 12Vand the micro runs at 5V Connecting 12V to a microcontroller pin would probably destroy the chip Fortunately wecan run most transistors at higher voltage and isolate the microcontroller from it Second the relay requires 33ma ofcurrent and the micro we are using is limited to 25ma We must use a transistor to drive the relay

The first step is to select a transistor The transistor must be able to handle the voltages and currents of theapplication In this case just about any NPN switching transistor will do The 2N2222 and is relations the 2N2222APN2222 etc are commonly used in these circuits A quick review of the transistor data sheet shows

Absolute Maximum RatingsSymbol Parameter Value

Vceo Collector-Emitter voltage 30V

Ic Collector current 600 ma

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Order Omron Parts AlliedEleccomOmron

Fast Shipping amp a Wide Selection Buy Online ampSave Time

Multisim Simulation wwwnicommultisim

Optimize circuit design performance with simulationLearn how

Figure 7-2

Our circuit uses 12V and will draw 33ma Clearly this transistor will easily handle this

The next step is to ensure we drive the transistor into saturation We will do this by selecting the proper value for

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 26: Micro Controller Interfacing

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

R1 As mentioned before transistors are current amplifiers The collector current will be the base current multipliedby the DC gain hFE One question is what is the hFE The data sheet for a PN2222 shows the hFE as a minimumof 35 under one set of circumstances and a minimum of 100 and a maximum of 300 under other circumstancesThat is a huge range What value should we use

The reality is that transistor parameters run all over the place The simplest thing to do here is use the worst casevalue or 35 in this case

Changing the transistor gain equation around and using the 33ma relay coil current and PN2222 hFE gives us

Ib = IchFE = 3335 = 94 ma

For simplicity we will round up Ib to 1ma Actually we will probably want to double it Tolerances in the value of R1the transistor and microcontroller suggest we should be on the conservative side Running Ib at 2 or 3 ma will notcause any damage and will give an extra margin to ensure the transistor is driven hard into saturation

One reason you might want to stay near the 1ma base current is if your application is battery operated and you wantto conserve every microamp to increase battery life In that case you would probably not be using a relay anyway sowe will use 2 ma as our base current for this example

The driving pin from the microcontroller will supply 5V There will be a voltage drop between the base and emitterVBE(sat) The data sheet shows this as 2V maximum with much higher base and collector currents that we will beusing In our circuit it will probably be in the 7V to 1V range For simplicity we will use 1V

Since the voltages across the circuit loop must be 0V we have the following

VP0 = VR1 + VBE

Solving for the voltage across R1 we get the following

VR1 = VP0 ndash VBE = 5V ndash 1V = 4V

So R1 will drop 4V with a current of 2ma Ohmrsquos Law says

R = VI = 4002 = 2000Ω

We will use a 2K resistor for R1 There are two more components in Figure 7-2 we have not accounted for D1 andR2 D1 is a diode to snub the current spike from the inductor coil A lot of energy is stored in the magnetic field ofthe relay coil when it is energized When we turn off the relay that energy has to go somewhere The collapsingmagnetic field will generate a current spike It sees a turned off transistor This current combined with a hightransistor resistance will be translated into a high voltage across the transistor possibly damaging it The diodeshould be put across all inductive loads including relays solenoids motors etc

The diode type is not too particular Diodes from the 1N400X family (1N4001 1N4002 1N4004) are commonly usedand inexpensive Their current rating is 1A and the 1N4001 has a breakdown voltage of 100V The other membersof the family have even higher voltage ratings

The remaining component is R2 and may not be needed in some applications When power is first applied to thecircuit you might get some current glitch through the transistor turning it and the relay on momentarily This mightnot be tolerable Putting R2 in will help prevent the transistor from turning on (no guarantees) by draining any chargeout of the base of the transistor 10K resistors are a typical value for this component

Letrsquos take a closer look the voltages across the relay and transistor We know we will have 12V from the supply andVcesat is going to be around 1 volt We know that the voltage across the transistor plus the voltage across the relaymust be 12V That means that the voltage across the relay must be

Vcc = Vrelay + Vcesat

Vrelay = Vcc ndash Vcesat = 12 ndash 3 = 117V

But our relay is a 12V relay Is it going to work Relays are very forgiving devices and will usually work at muchlower voltages than the nominal voltage The data sheet will usually have a specification like Must Close Voltage For a 12V relay this will usually be in the 9-10V range Keep in mind that the operating time will usually increase asthe voltage drops below the nominal voltage

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 27: Micro Controller Interfacing

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

It might seem to be a lot of work to calculate all this After you work with these circuits for a while you will just knowthat the value of R1 in not very critical and anything from 1K to 33K will work fine in most cases

Example Driving a high current LEDIn Part 4 we had an example of driving an LED directly by the microcontroller pin Inthis example we will assume we want to drive a bright blue LED The data sheetshows we want to run this at 50ma and the forward voltage drop across this LED is31V Letrsquos further assume that this is a portable device and we want to run it off a 9Vbattery The circuit has a 5V regulator to run the micro but we want to run the LED offthe 9V We will use a similar circuit to the relay driver above but like the LED circuitin Part 4 we need a current limiting resistor R2 The circuit is shown in Figure 7-3

From our earlier example we learned that the value of R1 is not too critical and justdecide to use a 15K resistor We want to control the current through the LED fairlyclosely so we need to consider a few things we ignored in the relay example We willfactor in the voltage drop (VCE) across the transistor switch for this application Thedata sheet says VCE(sat) = 1V max The conditions for this value are pretty high baseand collector currents which we are not using VCE will probably be closer to 3V forus and we will use that value

The LED circuit is driven by 9V The voltage around the circuit loop must be 0 so wehave

Vbat = VR2 + VLED + VCE

Rearranging this gives us

VR2 = Vbat ndash VLED ndash VCE = 9 ndash 31 - 3 = 56V

We now know that R2 will drop 56V and the current will be 50ma Ohmrsquos Law says

R = VI = 56 05 = 112Ω

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

ElectronicComponents3 billion electroniccomponents ampobsolete parts with nolead timeswwwamericaiicom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

MultisimSimulation

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoards

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 28: Micro Controller Interfacing

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

The nearest common resistor value is 110Ω sothat is what we will use

Note this circuit does not have a couple ofcomponents that are in the relay driving circuitWe donrsquot need the D1 diode across the LEDbecause the LED is not an inductive load Wealso removed the resistor from the transistorbase to ground We decided in this applicationthat a brief flash of light from the diode wouldnot be a problem when the device is firstturned on

Figure 7-3

Other considerationsIn both of the examples we had the transistor in a common emitter configuration meaning the transistorrsquos emitteris grounded The transistor is acting as a ldquolow side switchrdquo Since the transistor is a switch couldnrsquot we alsoconnect the NPN transistorrsquos collector to the power supply voltage and put the load between the emitter andground After all there are some cases we would like the load to be at ground potential

This will not work in most cases The reason is that the load will generate negative feedback causing thetransistor to try to turn off Suppose we tried that As the port pin started to go high current would flow throughthe base of the transistor causing current to flow into the collector and out the emitter though the load Thiscurrent would cause a voltage to form on the load As the voltage at the emitter rises the current through thebase would decrease causing a reduction in current through the transistor Essentially the transistor will not turnon properly in this configuration

If it is necessary to ground the load and use a transistor as a high side switch a PNP transistor will be neededThis will be covered in a future segment

SummaryWhen the load the microcontroller must control has voltage or current requirements that exceed the capability ofthe microrsquos output pin an NPN transistor can be used to switch the load Be sure the transistor can handle thevoltage and current requirements Gain and other specifications of transistors have a very wide tolerance rangeFortunately it is easy to make the design tolerant of component variations

Optimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

Dc to dc convertercircuitACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 29: Micro Controller Interfacing

Driving high power loads with transistors

httpwwww9xtcompage_microdesign_pt7_transistor_switchinghtml[27062011 13554 PM]

Created with the QTHcom SiteBuilder

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 6Microcontroller Interfacing Part 8

Back to Electronics Main PageHome Page

Gotcha Checklist1 Ensure the transistor can handle the voltage andcurrent required by the load

2 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

3 With an NPN transistor use a common emitter circuitwith the emitter grounded and the load on the collector

copy 2009 - 2011 Gary C Sutcliffe

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 30: Micro Controller Interfacing

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 8High Side PNP Transistor Switching

GoalsThis section covers the use of PNP transistors to perform high side switching with a microcontroller

High Side SwitchingPart 7 covered using transistors to switch loads that require higher currents or voltages than the microcontroller canhandle All the circuits had similar topologies The load was connected to the power source and an NPN transistoracted as a switch to ground Since the switching element (the transistor) was at ground it is called a ldquolow sideswitchrdquo

With low side switching the load is at Vcc potential Sometimes it is desired to have the load at ground potential andto switch the power supplied to it This is called high side switching Figure 8-1 shows the difference between highand low side switching

You canrsquot just connect an NPN transistorrsquos collector to Vcc and the emitter to the load which is grounded Asexplained in the previous section negative feedback will prevent the NPN transistor from being driven into saturation

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Phase Perfect wwwPhasePerfectcom

Digital Phase Converters Perfectly balanced 3-phase power

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Figure 8-1

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Motors wwwapplied-motioncom

Matched Motors amp Drives from Stock Low CostSame Day Shipping

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 31: Micro Controller Interfacing

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

The alternative is to use a PNP type transistor Using PNP transistors is essentially the same as NPN transistorsexcept the polarities are reversed Figure 8-2 shows a circuit using a PNP transistor as a high side switch Noticethat the emitter is connected to the positive voltage The arrow in the emitter of a PNP transistor points in theopposite direction than in an NPN transistor Base current flows from the emitter to the base and collector currentflows from the emitter This is all backwards compared to an NPN transistor

The signal needed to control the PNP transistor is also reversed from NPN transistors With the NPN transistor youset the port pin to the high state to turn on the transistor With the PNP transistor you need to bring the port pin lowto turn on the transistor

The calculations for base current and the baseresistor are identical to those outlined in Part 7 forNPN transistors except the polarities arereversed

One additional thing you need to be careful withPNP high side switches is the voltage used todrive the load Normally it is best to use thesame voltage to drive the load that is used topower the microcontroller Consider thefollowing

Suppose the load voltage is +12V and themicrocontroller is running at 5 volts Ignore R2R2 would normally have a value high enough tohave little effect and ignoring it makes thecalculations that follow simpler Assume that P0is high at 5V and R1 is 1000 ohms Basecurrent would be calculated by

Ib = (Vcc ndash Vp0 ndash Vbesat)R1 =( 12 ndash 5 -7)1000 = 0063A = 63ma

Unless the transistor has exceptionally low gain itwill be turned on even though with P0 high itshould be turned off Worse yet themicrocontroller pin P0 will be seeing more than5V which greatly exceeds the usual limitation ofthe microcontroller supply voltage plus 03V Themicrocontroller would likely be damaged in thissituation Part 12 discusses ways of driving aPNP transistor when the load must be driven witha higher voltage than the microcontroller

Figure 8-2

The circuit in figure 8-2 contains two other components D1 and R2 D1 is a snubbing diode and is needed if theload is inductive like a relay solenoid or motor The previous section discussed the use of diodes across inductiveloads in more detail

R2 is used to keep the base pulled high if the microcontroller output pin is in the high impedance state which it isafter power up until the IO pins are configured This prevents the load from being powered until the microcontrollerhas active control of the transistor R2 might not be needed in applications where the load being briefly turned on

3 Atilde˜ Power Distribution wwwSpecPowercom

High Efficiency AC Solutions MIL STD Compliant -Custom Build

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 32: Micro Controller Interfacing

PNP Transistor Switching

httpwwww9xtcompage_microdesign_pt8_pnp_switchinghtml[27062011 13618 PM]

Created with the QTHcom SiteBuilder

will not cause problems say in an LED indicator This might not be tolerable in other applications such as controllinga motor or other load where improper operation might cause damage or other harm As a rule of thumb R2 shouldbe 10 times the value of R1

SummaryWhen the load must be at ground potential and the microcontroller cannot supply enough current a PNP transistorcan be used to switch the load from the Vcc side The circuit analysis is almost identical to using an NPN transistorexcept that the polarities are all reversed Be sure the transistor can handle the voltage and current requirements

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 7Microcontroller Interfacing Part 9

Back to Electronics Main PageHome

Gotcha List1 Donrsquot use the single PNP circuit to switch voltagesgreater than the microcontroller supply voltage

2 Ensure the transistor can handle the voltage andcurrent required by the load

3 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

4 You must set the port pin low to turn on the PNPtransistor With NPN transistors you set the port pinhigh

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

copy 2009 - 2011 Gary C Sutcliffe

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Atilde˜ Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

Inrush Current Limiters Available Online App Notes and Free Samples wwwamethermcom

Capacitor Switching Benedikt Jager Capacitor switching contactors BampJ USA 919 553 5501 wwwbnj-usacom

3 Oslash Power Distribution High Efficiency AC Solutions MIL STD Compliant - Custom Build wwwSpecPowercom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 33: Micro Controller Interfacing

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 9FET Transistor Switching

GoalsPrevious sections showed how to use bipolar transistors to switch loads with higher currents andor voltages than canbe handled by the microcontroller output pin directly This section shows how to use a different type of transistor theField Effect Transistor (FET) which can have advantages in some circuits

FET BasicsPart 7 described the operation of bipolar junction transistors (BJT) These transistors are known as current controlleddevices Essentially the collector current of a BJT is the base current multiplied by the gain of the transistor The FETis a voltage controlled device Like the BJT the FET has three pins These are the gate drain and source The gateis where the controlling voltage is applied

There are a number of FET types First there are N channel and P channel Then there are enhancement mode anddepletion mode variations Then there are other variations The most common type of FET in switching circuits is theMOSFET (Metal Oxide Semiconductor Field Effect Transistor) We will limit the discussion to N channel enhancementmode MOSFET These are the most commonly used FET in microcontroller based circuits Unless otherwise notedwhenever the term FET is used it will refer to an N channel enhancement mode MOSFET

The best way to look at an FET is as a voltage controlled variable resistor The resistoris between the source and drain pins The value of the resistor will depend on thevoltage between the gate and source (Vgs) If the voltage is zero volts the resistancewill be very high (several million ohms) and essentially be an open circuit If Vgs isabove a certain level the resistance will be very low (a few ohms or less) The datasheet will refer to this value as Rds (Resistance drain-source) If Vgs sometimesreferred to as just the gate voltage is in between these limits the resistance will besomewhere between low and high This is referred to the linear range Normally we willnot want the FET to be in the linear range in switching applications

To the microcontroller output pin the BJT base pin looks like a diode The pin mustdrive current through this diode The gate the FET control pin looks like a smallcapacitor between the gate and source pins The only current that flows is the amountneeded to charge or discharge this capacitance Once the capacitor is charged nofurther current will flow until the state of the microrsquos output pin changes

Example Driving a relayIn section 7 we used an example of a bipolar transistor to switch a relay We will revisitthat problem but this time use a FET as the switch Figure 9-1 shows the schematicThe problem is to control a 12V from the microcontroller output pin The resistance ofthe relay coil is 360 ohms Our 5V micro cannot directly switch 12V without risk ofdamage Ohmrsquos law also tells us

I = VR = 12360 = 033A or 33ma

Since the micro has a maximum sink and source limits of 25ma we fall short on thecurrent side as well We will use a FET to do the heavy lifting Letrsquos try a 2N7000 forthis application A quick look at the specs shows some key parameters

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

TransistorSearch Thousands ofCatalogs for Transistor

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 34: Micro Controller Interfacing

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

wwwglobalspeccom

Power fetCDI Stocks SEDI RFDevices Microwave ampMillimeterwave RFwwwcdiwebcomsedi

2N7000Vds 60V max

Id 200 ma max (continuous)

Pd 400 mW

Rds(on) 53 ohm (max)

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

DCDC ConverterCustom and StandardDCDC solutionsSpecification andSelection Guidewwwcalexcom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Inrush CurrentLimitersAvailable Online AppNotes and FreeSampleswwwamethermcom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Dc dc converterdesignACDC Power ModulesLow Cost GreatDelivery Standardand Customwwwcdiwebcomminmax

Analog mixedsignal ASICYour complex analogamp mixed signal ASICdesign specialistswwwLinearChipcom

5 Million ReasonsTo BuyAvnet Express -Quality ComponentsSame Day ShippingOrder OnlineAvnetExpressAvnetcom

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 35: Micro Controller Interfacing

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Figure 9-1

The maximum voltage across the device Vds is 60V so our 12V supply will not be an issue We calculated 33ma ofcurrent so we are way under the 200ma limit The power limit is 400 mW Assuming a worst case of 53 ohm Rds weget the following

Pd = I^2 R = 033 033 53 = 57 mW

The 2N7000 will be fine in this application Note the use of diode D1 It is used to steer the current produced by thecollapsing magnetic field caused when the FET is turned off Without the diode voltages high enough to cause damagecould be generate across the FET Diodes are needed whenever an inductive load is used

So why would we want to use a FET instead of a BJT A 2N7000 FET costs more than say a PN2222 BJT In thisparticular application there is probably not a big reason to use FETs There are some situations where a FET has oneor more major advantages

Consider a design for a portable battery operated device Battery life is a huge concern in our application so we wantto reduce current consumption in every part of the circuit we can Now instead of switching a power hungry relay weneed to turn on a component that requires 9V (from our battery) but only a few ma of current

In this situation we would probably drive the base of a bipolar transistor with a ma or more of current This current willbe an additional drain on the battery With a FET if the switching frequency is low the current into the gate of the FETwill be negligible Using a FET in this situation would save power

High Power SwitchingThe main situation where FETs are superior is in high current circuits Suppose we want to switch a motor electricalheater or other high current load FETs are produced with very low Rds the resistance between the drain and sourceThe lower the Rds the more efficient the circuit will be

Suppose we are making a heater for some application The heating element runs off of 24V and draws 8 amps when itis on Let first look at using a bipolar transistor A 2N3055 is a common high current transistor

2N3055Vce 60V (max)

Ic 15A (max)

Vce(sat) 3V (Ic = 10A Ib = 3A)

Our requirements for Vce (24V) and Ic (8A) are wellbelow the limits for the 2N3055 So far so good Nowlook at Vce(sat) It is 3V What happens when we run 8Athrough this

Pd = Vce(sat) Ic = 3V 8A = 24W

Those 24 watts are a lot of wasted power Not only thatbut that power is converted to heat We will need to use alarge heat sink to safely remove that heat Also look atthe transistor base current as the conditions for theVce(sat) It is 3A Our poor micro can only source 25maWe would need a circuit to boost the 25ma to 3A Thatwill add cost and complexity to the design

Letrsquos take a look at using an IRF530 FET The maximumvoltage Vdss and maximum current Id are well underthe operating conditions of our circuit We selected alogic level type FET so we can directly drive it with ourmicroprocessor The switching voltage is 2V well belowthe 5V the micro output line will supply We will be drivingthe FET fairly hard which is good but still below the 16Vmaximum

What about the power that is dissipated across the FET

Pd = Id^2 Rds = 8A 8 A 15 ohm = 96W

The power dissipated across the FET is still fairly high96W but is well under the 79W device limit and muchless than the 24W for the 2N3055 bipolar transistor The

IRF530Vdss 100V

Id 17A

Pd 79W

Rds(on) 15 ohm (Vgs = 4V Id=8A)

Vgs(th) 2V

Vgs 16V max

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 36: Micro Controller Interfacing

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

FET will still need heat sinking but it will not be nearly asdifficult as with the 2N3055

With a little bit of effort we could probably find a FET witha lower Rds further reducing the power dropped acrossthe FET

PWMFET transistors are often used to control DC motors What if we wanted to control the speed of the motor We cancontrol the speed of a DC motor by changing the voltage across it One way to do that with a microcontroller is to usePulse Width Modulation (PWM) Suppose we have a 12V motor If we just apply the supply voltage to the motor Itsees 12 volts and runs at full speed

Now suppose we turned the 12V on and off very fast The time on and time off are the same It is on 50 of the timeand off 50 of the time The signal is said to have a 50 duty cycle The average voltage the motor would see is50 of 12V or 6V The motor runs slower at 6V

Suppose we change the duty cycle to 75 The voltage is now on 75 of the time and off 25 of the time The motornow sees an average of 75 of 12V or 9V It runs faster than at 6V but slower than 12V We can create any voltagewe want between 0 and 12V by changing the duty cycle

Many microcontrollers have built in PWM peripherals Once you set them up they will run at the prescribed frequencyand duty cycle without any further attention If your micro does not have a PWM you can do the same thing with eitherhardware or software timers controlling the output

PWM circuits usually run at a few 10rsquos of KHz This can bring up a situation that if not accounted for can result in thedestruction of the FET Remember earlier we said that the gate looks like a capacitor to the microrsquos output line Thiscapacitor has to be charged or discharged each time the drive signal toggles While the capacitor is charging ordischarging the FET will not be either On or Off It will be in its linear range and the Rds will be between Rds(on) andRds(off) Current flowing through the FET will cause high power dissipation

In our examples above we didnrsquot turn the load on and off very fast so the FET has time to dissipate the extra heatbetween transitions and can be generally ignored If the FET is changing states 20000 times a second (10 KHzPWM rate) it will be spending a larger percentage of its time in this linear range It is possible that the powerdissipated by the FET in these conditions will exceed the maximums and destroy the FET

The amount of gate capacitance is really the gate charge and will be shown in the data sheet Higher power FETshave larger dies and thus will have a larger gate charge In such situations it is necessary to drive the gate willenough voltage and current to charge (discharge) the gate fast enough that the time spent in the FETrsquos linear region isvery short This is frequently done with special FET driver circuits or ICs Calculations and circuit board layouttechniques for high speed PWM are beyond the scope of this tutorial FET manufacturers have application notes thatgo into this subject in greater detail

SummaryFETs are an alternative to bipolar transistors for switching loadsbeyond the range of the microcontroller to directly control FETsare generally superior in applications where high currents arerequired and in some low power situations FET circuits requiresome special considerations especially at higher switchingspeeds

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power Management

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 37: Micro Controller Interfacing

Microcontroller drivign FET transistor

httpwwww9xtcompage_microdesign_pt9_fet_switchinghtml[27062011 13633 PM]

Created with the QTHcom SiteBuilder

Courses from Besser Associateswwwbesserassociatescom

Molex Products In StockFind the Molex Products You Need and HaveThem Shipped TodaywwwAlliedEleccomMolex

Gotcha List1 Ensure the FET can handle the voltage and currentrequired by the load

2 Consider logic level switching FETs to simplify interfacingto microcontrollers

3 Protect the transistor with a snubbing diode if the load isa relay solenoid motor or otherwise inductive

4 High power PWM applications must consider driverequirements to overcome gate charge

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 8

Microcontroller Interfacing Part 10Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

Inrush Current LimitersAvailable Online App Notes and Free Sampleswwwamethermcom

Capacitor SwitchingBenedikt Jager Capacitor switching contactorsBampJ USA 919 553 5501wwwbnj-usacom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Analog mixed signal ASICYour complex analog amp mixed signal ASICdesign specialistswwwLinearChipcom

Power Switches amp RelaysOrder Power Switches amp Relays Now Searchand SavewwwDowKeycom

Power ManagementCourses from Besser Associateswwwbesserassociatescom

Order Molex PartsFast Shipping amp a Wide Selection Buy Online ampSave TimeAlliedEleccomMolex

Electric Motor Starters14 - 600 HP UL508E rated In-Stock LowPrices Same Day Shipwwwfactorymationcom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 38: Micro Controller Interfacing

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 10Input Protection

GoalsIntegrated circuits (ICs) are made up of sensitive transistors Most are rated for 3 to 5 Volts DC although newerones operate at even lower voltages Exceeding that voltage can damage or destroy the IC Electro StaticDischarges (ESD) from human contact can exceed 10000 Volts This section describes methods for protectingmicrocontroller inputs

Static Electricity Input Protection with RC filteringSemiconductors are really fragile critters If you exceed the maximum voltage you can burn it out If the inputvoltage goes below ground by more than a few tenths of a volt the whole IC can latch up in a high current modeand burn up Static electricity can build up on the user and then discharge through your circuit when they touch aswitch or other control Putting some protection on the inputs can be a good idea

Figure 10-1 shows a switch configuration similar to that shown in Part 6 Two additional parts are added R2 andC1 Adding just R2 by itself will provide some protection If a voltage spike is applied to the switch the resistor R2will limit the current flowing into the input port Typically R2 will be between 10 and a few hundred ohms

Adding C1 will improve protection to the input A capacitor resists change in the voltage across it The capacitor willbecome charged as current flows into it The amount of current will be limited by the value of R2 The time it takesto charge to the input voltage will increase as the capacitance of C1 and the value of R2 increases Figure 10-2shows the voltage across a capacitor with a step input

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Web ApplicationFirewallPrevent Zero DayAttacks Facilitatescompliance with PCItrustwavecom

Printed CircuitBoards

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 39: Micro Controller Interfacing

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Figure 10-1 Flex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Assume that the input voltage Vin and voltage across the capacitor Vc is zero volts Atsome point Vin jumps to the value V At that instant Vc is still zero volts Over time thecapacitor will start to charge and if Vin stays at V long enough Vc will approach V Therate Vc approaches V depends on the time constant (TC)

TC =RCWhere R is resistance of R in ohms and C is capacitance of C in Farads TC ismeasured in seconds

The voltage at time t can be calculated with the following equation

Vc=V(1-e^(-tRC))

At a period of 1 TC Vc will reach about 63 of V At 2 TCthe voltage will reach 63 of the remaining differencebetween Vc and V or about 86 of V and so on At 4 TC Vc will be within 99 of V Technically Vc will neverreach V but the difference will be infinitesimal At somepoint Vin returns to zero volts and the capacitor will

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

Bandpass filterscustomCustom and Stdbandpass filters LCCavity Ceramic SAWfilterswwwanatechelectronicscom

Miraco FPCOptionsFlexible PrintedCircuits and OtherInterconnect SolutionsOptionsMiracoInccom

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

5 Pin ModulesState of the ArtProtection ModulesCompetitive Pricinglea-networkscom

EMC Mid-Tier VNXStorageSimple EfficientStorage by EMCStarting Under $10KFree VNX DemowwwemccomVNX-Data-Phellip

PowerManagementCourses from BesserAssociateswwwbesserassociatescom

Flexible PrintedCircuitsSpecializing in FlexiblePrinted Circuitdesigns call MiracotodayMiracoInccom

CapacitorSwitchingBenedikt JagerCapacitor switchingcontactors BampJ USA919 553 5501wwwbnj-usacom

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 40: Micro Controller Interfacing

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

discharge at the same rate it charged

Now consider the situation where Vin is at voltage V for ashort period of time The capacitor will not have time tocharge very much and Vc will not be able to approach V If the length of Vin being high is short compared to TC Vcmay not get high enough to reach the threshold voltage ofthe microcontroller input The microcontroller will neverrecognize the input signal went high

Letrsquos get back to our static electricity problem A staticelectricity burst is usually a very short pulse The RCcircuit will limit how high the voltage will get A resistor ofa couple of hundred ohms and a capacitor of 01 or 1microfarads will give reasonable protection to the input

Figure 10-2

An RC circuit is also known as a low pass filter If the period of a signal is long (low frequency) compared to TC thesignal will pass through reasonably intact If the period is short with respect to TC it will be filtered out

The low pass filter can be used for other purposes Part 6 mentioned switch bounce This is where a mechanicalswitch will often make and break contact when it is actuated Proper values of RC can filter out these spikes RCfilters are also used for filtering out high frequencies for AD (Analog to Digital) converters Their use in thoseapplications will be covered in a future installment

The nature of the signal inputs must be kept in mind when using RC filtering Suppose we have a sensor thatindicates one revolution of a motor If the motor is running fast enough or if the values of R and C are too high theinputs will be filtered out The voltage at the pin will never reach the switching threshold and the micro will think themotor is not running

Looking at the situation from the analog world an RC circuit has a frequency at which point frac12 of the input voltage islost This is also known as the 3dB point This is known as the cut off frequency or Fc

Fc = 1(2πRC)The frequency of a signal going through an RC filter must be much less than Fc for proper operation

Another characteristic of an RC filter might be important in some applications Take a look at Figure 10-2 Supposethat our application requires the microcontroller to perform some operation very quickly when Vin rises to V Furtherassume that the threshold voltage for determining the input registering as a 1 or a 0 is at frac12 V It takes nearly 1 fullTC for Vc to reach that voltage This might be too late for the microcontroller to complete its operation in time

Some microcontroller inputs depend on the input signal rising quickly Reset pins and edge triggered interrupt linesmay not work properly if an RC circuit slows the rate the signal changes Consult the microcontroller data sheetbefore putting RC networks on these types of microcontroller inputs

Zener Diode ProtectionFigure 10-3 shows an input protected with a zener diode A zener diode acts like a regular diode with one exceptionIf the reverse voltage reaches a certain point the diode willstart to conduct In combination with R to limit the currentand drop the excess voltage the voltage seen by the inputwill never exceed the zener voltage Vz This of courseassumes the input signal does not exceed the ratings ofthe zener diode or resistor

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 41: Micro Controller Interfacing

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Select a zener diode with a Vz that is higher than the Vccpowering the microcontroller but less than the voltage thatwill cause damage For 5V systems 51V zeners such asthe 1N5231 and the 1N4733 are commonly used

Transient Suppressor ProtectionSpecial electronic components specifically designed forESD protection are available The go by the name of TVSMOV and a large number of trade names They are easyto use and have many advantages over the zenerprotection including faster response times and higherenergy capacity Some are also available as arrayshandling a number of signal lines in a single packageFigure 10-4 shows a microcontroller input protected by oneof these devices The schematic symbol may varydepending on the technology of the device

In normal operation these look like a capacitor If theapplied voltage reaches the Varistor Voltage the varistoracts like a switch shorting the signal to ground Most typesare bidirectional meaning they will switch on if the varistorvoltage is reached regardless of polarity

The first data sheet parameter to look for is the MaximumAllowable Voltage This must be higher than the normaloperating signal voltages Otherwise the normal signal willtrip it possibly preventing the signal from reaching thethreshold voltage Another key specification is thecapacitance You will want to use low capacitancesuppressors for high frequency signals Otherwise thesignal will get filtered out as in the RC filter describedearlier Another specification is the maximum surgecurrent The higher this is the more abuse the circuit cantake but often at a higher cost size and capacitance

Figure 10-3

Figure 10-4

Since transient suppressors look like capacitors during normal operation you need to consider the same frequencyrelated considerations as if you had used a regular RC filter The resistor is optional Use one between 10 and a fewhundred ohms for things like user switches Leave the resistor off and use low capacitance types for high frequencysignals

SummaryIt is a dangerous world out there For tough environments or equipment with high reliability requirements inputprotection is called for RC filters zeners and transient protectors are some of the methods that can be used toprotect your sensitive microcontroller circuit

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 42: Micro Controller Interfacing

Microcontroller Input Protection

httpwwww9xtcompage_microdesign_pt10_input_protectionhtml[27062011 13646 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure the cut off frequency of the RC network ishigher than the desired signal

2 Protection devices can affect the accuracy andmaximum conversion rates of AD inputs

3 Check the microcontroller data sheet before puttingRC networks on reset or edge triggered interrupt inputs

4 RC networks add a delay This will affect how fastyour microcontroller can react to an input change

5 Select zener voltages and varistor voltages above thenormal operating voltages of your system

Circuit oscilloscope wwwtekcom

8 Out of 10 Engineers Rely on Our OscilloscopesCome See Why Today

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 9

Microcontroller Interfacing Part 11Back to Electronics Main Page

Home Page

copy 2009 - 2011 Gary C Sutcliffe

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Printed Circuit Boards wwwcirexxcom

Flex Circuit Rigid-Flex Boards Manufacturing PCBServices

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

EMC Mid-Tier VNX Storage wwwemccomVNX-Data-Prote

Simple Efficient Storage by EMC Starting Under$10K Free VNX Demo

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Capacitor Switching wwwbnj-usacom

Benedikt Jager Capacitor switching contactors BampJUSA 919 553 5501

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 43: Micro Controller Interfacing

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 11Using Optoisolators for Inputs

GoalsThis section discusses using optoisolators sometimes called optocouplers or simply optos to provide isolationbetween the microcontroller and the outside world This type of component incorporates a photo transistor (usuallyNPN) and an LED in the same package It is a very useful device when you want to have a very high isolationbetween your microcontroller and the outside world As discussed in Part 10 itrsquos a dangerous world out there

Optoisolator CharacteristicsEarlier sections of this series discussed interfacing to LEDs (Part 4) and transistors (Part 7) Since optoisolatorscombine both of these components the reader is advised to be familiar with those sections This section will usemany of the concepts of the earlier sections

Light from the LED turns the transistor on Since there is no physical connection between the transistor and the LEDthere is excellent voltage isolation The opto will provide isolation of 1500V or more depending on the deviceselected

A number of companies make optoisolators A common family is the 4N3x series Figure 11-1 shows an optodriving an input This section will use the 4N32 as an example Note there is no physical connection from Vin andthe rest of the circuit to the right

As described in Part 7 assuming the transistor is not in saturation the collector current will be equal to the basecurrent multiplied by the gain With an opto the base is isolated and the base current depends on current from thephotoelectric effect of photons from the LED on the transistor

The amount of base current generated from the photons is not very high Because of this many optos use a circuitknown as a Darlington pair The opto in Figure 11-1 uses this circuit Light from the LED falling on the firsttransistorrsquos base causes current to flow through its emitter This emitter current flows into the base of the secondtransistor The amount of collector current in the second transistor will be the base current of the first transistormultiplied by the gain of the first transistor multiplied by the gain of the second transistor The Darlington circuitprovides very high gain

The total gain will be shown as the transfer ratio onthe spec sheet This is defined as the ratio of thetransistors collector current (Ic) and the LEDrsquos forwardcurrent (If)

Tr = IcIfLike the gain of a transistor transfer ratios can vary alot and are usually specified as a guaranteedminimum value Fairchild Semiconductor specifiesthat their 4N32 has a minimum transfer ratio of 500This means that if the output transistor is not insaturation the output collector current will be at least5 times the LED current

Example Isolating an inputIn this example we will consider using an optoisolatorto interface a 12V signal to our microcontroller Figure11-1 shows a typical circuit Ignore D1 for the time

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 44: Micro Controller Interfacing

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Figure 11-1being In most cases this can be eliminated from thecircuit

The first step is to determine the value for R1 the LED current limiting resistor The spec sheet for the 4N32 says themaximum continuous forward current for the LED is 80ma We donrsquot want to exceed that Many of the parameters onthe spec sheet say the test case is 10ma That is a good value to us if our application will allow that much current fromthe signal source

From Part 4 we learned the current limiting resistor can be calculated if we specify the current and know the forwarddrop For the 4N32 the typical forward drop is 12V Thus

R = (Vin-Vf)If= (12-12)01= 1080 ohmsYou wonrsquot find a 1080 ohm resistor even if you specify 1 resistors The actual value is not critical so you can use a10 or 12K resistor

The next step is to determine the value of R2 the transistorcollector load resistor The value for this is not very criticaleither A 10K resistor works well in most cases Assume themicrocontroller is powered by 5V The 4N32 data sheetshows Vce-sat is 1V The current through the opto with a10K resistor will be

I = (Vcc-Vce)R= (5-1)10000= 4maThis is well below the maximum opto collector current of150ma Letrsquos do a quick sanity check Letrsquos say we pickedthe 12K resistor The LED current will be

If = (Vin-Vf)R= (12-12)1200= 009 = 9ma

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Ground Loop Isolators wwwadtech-instcom

Signal Conditioners and Temperature TransmittersCustom Designs

Flexible Printed Circuits MiracoInccom

Flexible Printed Circuit amp Other InterconnectSolutions Experts

Multiply the 9ma by the transfer ratio of 500 and we get the collector current of 45ma This is well above thesaturation current of 4ma (limited by the 10K R2) We will be driving the output well into saturation which is what wewant

Couplers OptoToshibacom

TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V20Mbps IC coupler

Special Summer Offer wwwcuflexcom

Flexible Circuit Prototypes $90000 limited timeonly Made in USA

Search Avnet ExpressAcircreg AvnetExpressAvnetcom

5 Million Parts Expert Service amp Same DayShipping Order Online

Analog mixed signal ASIC wwwLinearChipcom

Your complex analog amp mixed signal ASIC designspecialists

KNICK Signal Isolators wwwknick-usacom

Signal Conditioners Analog Digital Current VoltageTemp Strain Res

Analog Mixed Signal wwwbesserassociatescom

Courses from Besser Associates

Miraco FPC Options MiracoInccom

Flexible Printed Circuits and Other InterconnectSolutions Options

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 45: Micro Controller Interfacing

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Input Example VariationsLetrsquos say our source signal canrsquot drive the LED with that much current Select the value for R1 to allow the current itcan drive Multiply that by the transfer ratio to find what the theoretical collector current will be If this current isseveral times the saturation current (4ma in the example above) you will be OK

You have a couple of options if the LED current multiplied by the transfer ratio is too low You might be able to use alarger value for R2 This will reduce the saturation current You might also want to increase the value of R2 if yourmicrocontroller circuit needs to run on very low power In the example above 4ma is not a lot of current but in abattery powered device every micro amp adds up

Why not just make R2 very large to start with Why not make it 1M ohm or more right from the start The problem isthat it will take very little current to drive the output to saturation Small noise spikes can give false responses Youcan also get situations where leakage currents on the circuit board can cause the circuit to fail The oils from solderflux finger prints or other sources can collect dirt over time and allow minute current flows that will cause problems

There is another spec on the data sheet called ldquodark currentrdquo This is the collector current that will flow even if there isno light from the LED Typically these are measured in nano-amps but there can be an appreciable drop across theload resistor if it has a very high resistance value

If you must run your circuit near the edge with a high value opto collector load you might need to put in resistor fromthe opto pin from the transistor base to ground The base pin is not connected in Figure 11-1 This resistor will help tokeep the transistor or Darlington pair turned off when no signal is present The value for this situation might need tobe determined by trial and error Typical values will range from 100K to several meg-ohms depending on yourcircuit

Besides providing excellent isolation from the outside world the reader might have noticed that the opto also acted asa voltage level translator It converted the 12V input signal to the Vcc level used by the microcontroller This isconvenient but one has to consider the Vce-sat the voltage across the collector and emitter of the output when theoutput is turned completely on This is especially true if the microcontroller is using a Vcc less than 5V

The Fairchild 4N32 lists the Vce-sat at 10V (maximum) This means thatwhen the LED is driven and the output is turned on to saturation 1V couldbe present at the microcontrollerrsquos input not the zero volts we normallyexpect for a logical 0 If you were using one of the low voltage micros withVcc at 18V or less the circuit would never register a logical zero

If you find yourself in this situation consider using an opto with a singletransistor output instead of a Darlington It will have a lower Vce-satAnother option would be to use an opto with an FET output These looklike a very low value resistor when turned on and can get logical 0voltages very close to ground FET output optos are often called solidstate relays and tend to be more expensive than optoisolators with bipolartransistor outputs

When writing code for your application keep in mind that there is a phase inversion of the input signal The conditionthat causes voltage to be applied at the optorsquos LED input will cause the microrsquos input to read as zero and vice versa

Example AC inputsLetrsquos say your application needs to sense AC line voltage Your application might need to know right away if the ACpower is lost so it can store some critical values or put something into a safe state A simple way to do that is to connecta low voltage UL rated wall transformer to the opto LED For this example assume that we picked a 12V AC walltransformer It is important we used an AC version instead of the more common DC wall wart because we want to seeeach cycle of the AC

Because it is 12V we could start with the resistor values we used in the DC example above but there are a couple ofother considerations because it is AC First of all AC transformers will vary in the output voltage With a lightly loadedcircuit like this they will tend to exceed the nominal rating They will read even higher if your line voltage is on the highside You might want to start by assuming your wall wart is going to put out 15V to start

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 46: Micro Controller Interfacing

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

The 12 volt rating is based on its RMS value The peak value will be 14 times the RMS value If we assume that our12V transformer is really going to be 15V the peak voltage will be 15 times 14 or 21volts peak-peak

You could specify the limiting resistor for 21 volts but you will probably get conditions where the voltage doesnrsquot get thathigh and the circuit wonrsquot work Quite a dilemma

A practical solution is to design for the nominalvoltage and verify that the peak wonrsquot causedamage If we used 12K for R1 in Figure 11-1we would know it would work fine at 12VAC Ifwe assume a peak of 21V the LED current atthe peak would be

I = (Vin-Vf)R= (21-12)1200= 0165 = 165maThe 165 ma is well below the 80ma maximumcurrent specified for the 4N32 so we are safeIf one is especially paranoid the value for R1could be increased to 15 or 2K

Figure 11-2

Figure 11-2 shows the wave forms for the AC input and the output of the opto The blue line represents the AC signalapplied to Vin in Figure 11-1 The red signal is the output of the 4N32 optoisolator and what the microcontroller input pinPO sees The first thing to notice is the output is low only during the positive half cycle of the input We will get one lowpulse every 160 of a second in the US and 150 of a second in many other places of the world

Another thing to notice is that near the zero crossing we donrsquot get the low output This is because the LED needs about12 volts to turn on and then provide enough LED current to produce enough light to turn on the transistor This is OK ifwe are just detecting the presence of line power but must be accounted for if we want to synchronize with the linevoltage phase

Take a look at what happens during the negative half of the AC cycle With the conditions described above we couldhave 21V reverse biasing the LED The spec sheet says the reverse voltage must not exceed 3V Putting this muchreverse voltage will change the Light Emitting Diode (LED) into a Darkness Emitting Arsenide Diode (DEAD)

A simple solution to this problem is to install D1 It will conduct current during the negative half cycle and limit thereverse voltage across the LED to about 7 volts Diodes like the 1N400n series work well for this

Speed considerationBy electronic standards optoisolators tend to be rather slow Generally they turn on reasonably fast but turn offsomewhat slowly The 4N32 can take 5 usec to turn on and 100 usec to turn off under some conditions This might befine for your application but it might be an issue for high frequency signals or for high speed data communications

The slow turn off is due to internal capacitance inside the output transistors Using a low value load resistor willdischarge this capacitance faster but at higher current consumption There are some optos designed for high speedapplications Using one might be the preferred solution

SummaryAn optoisolator can protect microcontroller circuits since there is no physical connection between the microcontroller andthe outside world The only connection is a beam of light Besides providing isolation optoisolators provide a convenientway to interface higher voltages and AC to microcontroller inputs

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 47: Micro Controller Interfacing

Using Optoisolators to microcontroller inputs

httpwwww9xtcompage_microdesign_pt11_opto_inputshtml[27062011 13658 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Ensure that the input has enough voltage to overcomethe drop of the LED

2 Donrsquot exceed the maximum LED current

3 Be sure the Vce-sat of the output transistor is belowlogic zero voltage levels

4 Protect the LED from reverse over voltage if you arefeeding it with AC

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 10Microcontroller Interfacing Part 12

Back to Electronics Main PageHome

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

Multisim Simulation Optimize circuit design performance with simulation Learn how wwwnicommultisim

Power Management Courses from Besser Associates wwwbesserassociatescom

copy 2009 - 2011 Gary C Sutcliffe

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

PCB - Introductory Offer 2 Layers $25ea - 4 Layers $50ea Even 1 piece is Ok - No Tooling wwwPCBnetcom

Discover Your PCB Partner Easy PCB Solution - Design-Printed Circuit Board Fabrication-Assembly wwwelectrocircuitcom

Couplers TLP117 - 5V 50Mbps IC coupler TLP2066 - 33V 20Mbps IC coupler OptoToshibacom

Printed Circuit Boards Flex Circuit Rigid-Flex Boards Manufacturing PCB Services wwwcirexxcom

Analog mixed signal ASIC Your complex analog amp mixed signal ASIC design specialists wwwLinearChipcom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 48: Micro Controller Interfacing

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Home Electronics Tropical Fish Garden Ham Radio

Microcontroller Interfacing ndash Part 12Using PNP Transistors to Switch Higher Voltage Loads

GoalsThe easiest way to switch a higher power load than a microcontroller can handle is to use an NPN transistor asexplained in Part 7 Part 8 showed how to use a PNP transistor allowing the load to be at ground potential as issometimes necessary One limitation with the circuit described in Part 8 is that the load canrsquot run on a voltagehigher than the microcontrollerrsquos supply voltage This chapter shows how to drive a load that must be at groundGotcha List

1 Be sure both transistors can handle the voltage supplying the load

2 Ensure the PNP transistor can handle the current required by the load

3 Pick a PNP transistor with good gain to minimize base current requirements and excessive power consumption

4 Protect the transistor with a snubbing diode if the load is a relay solenoid motor or otherwise inductive

potential but run on a voltage higher than the microrsquos supply voltage

High Side SwitchingThe circuits described in Parts 7 and 8 are pretty simple and if the application allows are a good way to goUnfortunately your application may have requirements that those circuits wonrsquot meet Automotive applications forexample usually require driving a grounded load with 12V Figure 12-1 shows one way to accomplish this In thiscircuit microcontroller port pin P0 turns NPN transistor Q1 on and off Q1 in turn handles the higher voltage andcurrents that the micro canrsquot handle to turn PNP transistor Q2 on and off Q2 acts as the switch that suppliespower to the load

Letrsquos suppose the load is a 12V lamp that runs at 5 A The first step is to select the transistor that switches theload A search though our parts bin produces a TIP32C transistor in a TO-22 case That looks beefy Will it work Table 1 shows some key specs Note that the specs for the TIP32 have negative numbers This is backwardsthan specs for NPN transistors This is because current directions are in the opposite directions with the twotransistor types Base current flows into an NPN transistor but flows out of a PNP transistor We can ignore thepolarity when we do the calculations

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 49: Micro Controller Interfacing

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Figure 12-1

Vceo is -100V That is well above the 12V that drives the load It can handle 3A ofcollector current which is well above the load current so it looks like a good candidate The next step is to determine what it will take to drive a TIP32

The minimum HFE or gain of a TIC32C is 10 with a collector current (Ic) of 3A is 10 We wonrsquot be switching nearly that much current and the HFE will be higher under thoseconditions but we want our designs to be reliable and reproducible so we use theconservative value of 10 The collector current of a transistor is the base currentmultiplied by the gain

Ic = Ib HFERearranging the equation gives us

Ib = IcHFE = 5A 10 = 05A or 50maThis means that transistor Q1 must sink at least 50ma Another important parameterfor Q1 is to be able to handle the load supply voltage V+ on Figure 12-1 Anothersearch of the parts bin produces a 2N2222A transistor Its specs are in Table 1

From our calculations above Ib2 is 50ma minimum Ib2 is also the collector current ofQ1 if you ignore current supplied by R3 which we will do for now We need to select avalue for R2 that will allow 50ma to flow from V+ through the emitter-base junction ofQ2 through R2 and into the collector of Q1 Thus Ib2 is the same as Ic1Ohmrsquos law tellsus the value of R2 is

R2 = Vr2Ir2We know that the current through R2 Ir2 is 50 ma What is the voltage across R2That will be V+ (12V) minus the base emitter voltage Vbe(sat) of Q2 and the Vce(sat)of Q1 From Table 1

Vr2 = V - Vbe2 - Vce1 = 12 -18 - 3 = 99 VKnowing the voltage across R2 and the desired current Ohmrsquos Law says

R2 = VI = 9905 = 198 ohms

TIP32C Key SpecsVceo -100V

Ic -3A

Vce(sat) -12V

Vbe(sat) -18V

HFE (I c =3 A) 10

2N222A Key SpecsVceo 40V

Ic 600ma

Vce(sat) 3 V

Vbe(sat) 12V

HFE (Ic = 150ma) 50

Table 1

Since 198 ohms is not a standard resistor value we will use a 220 ohm resistor I mightconsider using a the next standard value resistor less than 198 ohms to increase thecurrent and improve the margins The problem here is that 50ma is quite a bit of currentfor a resistor Consider this

Miraco FPCOptionsFlexible Printed

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 50: Micro Controller Interfacing

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

P = IIR = 050 050 198 = 495WWe will need at least a 12W resistor If we use a lower value resistor the current willincrease slightly but since power is related to the square of the current the powerdissipated will go up fast So what do we do So far we have been conservative in ourestimates and used a worst case value for HFE the gain of the transistor Chances arethe gain will be much higher than 50 so we could get by with less base current maybequite a bit less

If I were just making one or two copies of this circuit and these were the only PNPpower transistors I had on hand I would try a larger value for R2 maybe approaching1K I could tweak the circuit until it worked properly and did not burn up resistors If Iwere designing a circuit for mass production this would be a bad idea Sooner or later abatch of boards would be produced where the components had a mix of parameters thatdid not work Or worse yet they would test OK in the factory but fail in the field

In a production design a better option would be finding a PNP power transistor with ahigher gain so less base current would be required One option might be a Darlingtontransistor Darlington pairs are two transistors in an array so the gain of the twotransistors are multiplied together to give the gain of the device One possible part is aTIP117 which has a minimum gain of 500 A TIP117 would only need 1ma or 150th the base current of the TIP32 we started with Rather than start all over in thecalculations we will continue the design with the TIP32C

The next step is to calculate the value for R1 R1 will limit the base current through Q1 Since Q1 is acting as a switch to turn on Q2 we need to drive Q1 into saturation Weknow the base current multiplied by the gain will be the collector current Switching thatequation around and plugging in the parameters for Q1 a 2N2222 we had in our partsbox we get

Ib1 = Ic1HFE = 05050 = 001AWe have the current through R1 Now we need the voltage across it As explained inPart 2 the voltage across the loop must be zero Since the micro is running off 5V thevoltage at P0 when it is set high will also be near 5V Other than the resistor R1 theonly other circuit element in the loop is Q1rsquos base-emitter junction The data sheet saysthis value Vbe(sat) = 12V So

Circuits and OtherInterconnect SolutionsOptionsMiracoInccom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Analog MixedSignalCourses from BesserAssociateswwwbesserassociatescom

Printed CircuitBoardsFlex Circuit Rigid-Flex BoardsManufacturing PCBServiceswwwcirexxcom

MultisimSimulationOptimize circuit designperformance withsimulation Learn howwwwnicommultisim

Solid State RelaysManufacturer of DINand Panel mount solidstate relayassembliesanaconpowercom

3 Atilde˜ PowerDistributionHigh Efficiency ACSolutions MIL STDCompliant - CustomBuildwwwSpecPowercom

WireWorksElectrical CAD1 software forelectrical design witha library amp BOM - seea demowwwjavelin-techcomelecthellip

Analog mixedsignal ASICYour complex analogamp mixed signal ASIC

All Flex PrintedCircuitslow to mediumvolume flex circuitsquick turn amp flexcircuit assemblywwwallflexinccom

UnderstandingDSPthe Rick Lyons Courseonly from BesserAssociateswwwbesserassociatescom

Special SummerOfferFlexible CircuitPrototypes $90000limited time onlyMade in USAwwwcuflexcom

Flex Circuit BoardsAll in One PCBSolution Services PCBDesign Fabrication

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 51: Micro Controller Interfacing

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Vr1 = Vp0 ndash Vbe = 5 ndash 12 = 38VBy Ohmrsquos law

R = VI = 38001 = 3800 or 38K ohmsThese values will give 1ma of base current though Q1 That is probably enough but we can increase it quite a bit andgive more margin for out of spec parts and other real world issues by using a lower value resistor Letrsquos pick a 22Kresistor Plugging that in

Ib1 = VR =382200 = 0017AThis would give us a collector current of

Ib HFE = 0017 X 50 = 086AThis is more than the 050A required to drive Q2 into saturation Just to be sure this value will not cause problems wesee that the maximum base current for a TIP32C Ibmax is 3A and Ic for Q1 is 6A This is not even close to thelimits of our transistors

We now only need to figure the values of a few morecomponents The first is R3 When we want the load turned offthe base off Q2 must be at a voltage near or higher than itsemitter R3 will supply that voltage The only thing we need tobe concerned with is if the value is too low and Q1 is turned oncurrent will flow through R3 and through R2 and Q1 If the valueof R3 is too low there will be more current through R2 whichwill raise the voltage of the base of Q2 This could prevent Q2from fully turning on

A good rule of thumb would be to make R3 at least 10 times the value of R2 This will not increase the currentthrough Q1 and R2 much We already checked to see that we are not near the maximum collector current for Q1 soa bit more wonrsquot harm anything

The final resistor is R4 When the system is turned on there might be a some transient currents though P0 whichcould turn on Q1 and ultimately the load If the load is a motor or other device that could cause damage if the load isturned on until the micro is in full control R4 would help prevent (but not guarantee) Q1 from being turned on If theload is an LED or other device where a brief flash would not cause problems R4 can be left off A rule of thumb ofaround 10X the value of R1 will be a good starting point for this resistor

Finally there is D1 As explained in earlier sections we want to put the diode in the circuit if the load is inductive toprotect the switching transistors Motors solenoids and relays are all inductive loads If the load is purely resistiveD1 can be skipped

SummarySometimes the design requirements require more than a single transistor when the load requires more voltage andorcurrent than the micro is capable of handling Using an NPN transistor to drive a PNP transistor will allow driving agrounded load with higher voltages and currents

design specialistswwwLinearChipcom

Flex CircuitsampRigid FlexFlex Circuits Design toAssembly ThinkingFlex Think LenthorwwwLenthorcom

Assemblywwwcirexxcom

CellMite Model4325BDigital SignalConditioner withTEDS-Tag AutoIdentificationwwwelectrostandardscom

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching
Page 52: Micro Controller Interfacing

PNP Transistor switching

httpwwww9xtcompage_microdesign_pt12_hv_pnp_switchinghtml[27062011 13719 PM]

Created with the QTHcom SiteBuilder

Gotcha List1 Be sure both transistors can handle the voltagesupplying the load

2 Ensure the PNP transistor can handle the currentrequired by the load

3 Pick a PNP transistor with good gain to minimizebase current requirements and excessive powerconsumption

4 Protect the transistor with a snubbing diode if theload is a relay solenoid motor or otherwise inductive

Microcontroller Interfacing Table of ContentsMicrocontroller Interfacing Part 11

Back to Electronics Main PageHome

Rotary Position Sensor SENSOFOILAcircreg Ultra-flat membrane potentiometer standard amp custom wwwsensofoilcom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

CellMite Model 4325B Digital Signal Conditioner with TEDS-Tag Auto Identification wwwelectrostandardscom

copy 2009 - 2011 Gary C Sutcliffe

High Voltage Power Precision high voltage power for PMT and analytical instruments wwwkilovoltechcom

Avnet Express Acircreg Search 5 Million Parts Online Order Parts Online Avnet Express AvnetExpressAvnetcom

Try Our Free Parts Search Quality Parts since 1993 Stocking Supplier ISO 9001 wwwprelogtechcom

KNICK Signal Isolators Signal Conditioners Analog Digital Current Voltage Temp Strain Res wwwknick-usacom

Power Switches amp Relays Order Power Switches amp Relays Now Search and Save wwwDowKeycom

Ground Loop Isolators Signal Conditioners and Temperature Transmitters Custom Designs wwwadtech-instcom

  • w9xtcom
    • Microcontroller Interfacing - Introduction
    • Microcontroller Interfacing - Basic Electronics
    • Microcontroller Digital Output Basics
    • Interfacing an LED to a microcontroller
    • Microcoontroller Input Pin Basics
    • Interfacing switches to microcontrollers
    • Driving high power loads with transistors
    • PNP Transistor Switching
    • Microcontroller drivign FET transistor
    • Microcontroller Input Protection
    • Using Optoisolators to microcontroller inputs
    • PNP Transistor switching