# Measuring frequency of a signal above 5V with a microcontroller

I want to measure the frequency (up to 300 Hz) of a rectangle signal, that varies between 0V and Vtop, where Vtop is anything between 5V and 15V. Because I cannot apply more than 5V to the microcontroller (PIC16F1827), I need to limit the voltage somehow.

My first idea was to use a voltage divider. But then the 5V input signal would be to low.

The second approach is using an opamp (TS914). When I am powering it at 5V, the output would not exceed 5V. I already have this opamp in my design, to filter another voltage measurement. But when I look in the datasheet it says (In section "Absolute Maximum Ratings"):

The magnitude of input and output voltages must never exceed VCC+ +0.3V.

Should I add another opamp, e.g. LM324? The datasheet says (Input Common-Mode Voltage Range (Note 10)):

The input common-mode voltage of either input signal voltage should not be allowed to go negative by more than 0.3V (at 25˚C). The upper end of the common-mode voltage range is V + − 1.5V (at 25˚C), but either or both inputs can go to +32V without damage (+26V for LM2902), independent of the magnitude of V + .

So the LM324 would not be damaged, but would it work in my design (outputing a 5V rectangle signal)?

The last idea I had, are using zener diodes. Would this work?

What would you do to solve this problem? Is there another possability I didnt think about?

• The document that @Curd mentioned - TI - Latchup, ESD & other phenomena is superb and should be required reading for all circuit designers. HOWEVER do note that in section 3 where he cites comments they make about external protection diodes and series input resistors, the context and subject is transient electrostatic discharge - high voltage but well defined maximum energy, NOT applied external signals ongoing signals. Section 4 discusses the parasitic transistors that I have been referring to. – Russell McMahon Jan 29 '12 at 11:21

Summarised solution:

• A single transistor and 3 resistors will take a 0V \ "5V or more" signal and produce a 5V/0V output. With example resistor value, load on signal is about 80 uA at 5V and 250 uA at 15V. This can be reduce to say 8 uA/25 uA if desired and even lower if necessary. (Larger version of diagram below).

• A 390 ohm resistor and a 4V7 zener will do what you want provided you can tolerate 25 mA input current load.

• Use of an op amp allows slightly better results but the one transistor solution should be entirely adequate.

• NEVER allow the IC's clamping/protection diode to carry current during normal operation. You are inviting unreliability and unexpected and possibly inapparent operation all the days of your product's life. Doing this during normal operation always violates datasheet conditions.

• You MAY get away with afew uA or even a few 10's of uA and you may THINK you have get away with using them to carry 100's of uA. EVERY application that uses the protection diodes to carry more than half a whiff of current in normal operation is violating data sheet specs and inviting Murphy to lunch.
Results are unpredictable.
No professional design would do this.
App notes that recommend it are usually unprofessional.
See section at end of this answer.

Single transistor solution:

Input is shown as 5-15V but anything above about 4V will work.
When vin = 4V Vbase = R2/(R1+r2) x 4V = 0.6V.
This is notionally adequate, but at 5V you have more than enough drive.

R1 & R2 values shown are suggestions.
Values of eg 100k and 560 k could be used if appropriate R3 and high beta transistor was used.

Output is inverse of input. ie Vout is low when Vin is high.

R3 can be 10k or whatever suits.

Q1 to suit. I'd use a BC337 or SMD equivalent (BC817?)

If very low input current is wanted R1 and R2 can be increased greatly with some care. eg with R1 = 1 megohm, input current is about 15 uA at 15V and 5uA at 5 Volt. If transistor Q1 has a current gain of 100 (very safe for eg BC337-40) then Icollector = 500 uA so for a 5V swing R3 >= 10k so say 22k up is OK.

An extremely valuable fact to know about resistive dividers!!!

A little appreciated fact is that the ratio between two resistor values N places apart on a standard resistor scale is about constant.
This is implicit in the way the scale values are chosen.
The E12 resistor values are

1
1.2
1.5
1.8
2.2
2.7
3.3
3.9
4.7
5.6
6.8
8.2
(10, 12, 15 ... )

12 values and then the series repeats a scale of 10x higher.

So - the 56k and 10k values I have shown for R2 and R1 are 8 values apart. ie start at the 1 value above and count up 9 places and you get 5.6
ANY two values 9 apart have the same ratio (within the tolerance of the scale) and may be used to form an about equivalent divider.
eg any of 56k/10k, 68k/ 12k, 82k/15k 100k/18k etc.

A zener diode + a resistor will do what you want as long as the load on the input circuit is acceptable. If you want to reduce the load then an opamp based design would be better.

The On page 350 of the datasheet it gives high and low input voltage levels. Which level suits depends on which input pin you are using but the safest value is >= 0.8 x Vdd or at Vdd = 5V, Vinhi >= 4V.
The datasheet also notes that Vin must not be greater than Vdd + 0.3V ABSOLUTE MAXIMUM (even if not operating correctly) and in practice anything over Vdd would be risky.

WARNING:

Curd's recommendation to use a diode clamp to Vdd is common practice but very risky as it WILL inject current into the IC in places unintended by the maker during normal operation. Results will vary and will be unpredictable. Using a Shottky rather than a silicon diode makes this less risky but still ill advised and it violates even the absolute maximum manufacturer's spec.

Zener clamp:

This simple circuit may well be enough.

What is important is to ensure that Vout meets your spec at all times. Many people use a xx Volt zener diode and assume that they will get XX volts. At low currents this is often far from true. The curves below show zener voltage with current for typical zeners. Note that the 4V7 zener requires about 1 mA of current to drive it to above 4V. If we design for 2 mA minimum all should be well. This produces a perhaps unexpected result.
5V in. i = 2 mA. Vzener expected = 4V2.
R = (5V - 4.2)/0.002 A = 0.8/0.002 = 400 ohms.
Say 390 ohms = standard E12 resistor value.

At 15 V we expect current to be ABOUT (15-5)/400 = 25 mA.

25 mA may be more than you wish to allow.

A lower range of Vin will allow a lower Imin- Imax range and Vin min a few volts above 5V would also help greatly.

Power in resistor = V x I = (15-5) x 25 mA = 250 mW = 500 mW resistor.

Zener current voltage curves V02 x2.jpg

Example zener datasheet

PROTECTION DIODES:

Many people are unaware of or just ignore the datasheet distinction between "Absolute maximum" ratings and recommended operating conditions.

Absolute maximum ratings are those which the device is guaranteed to survive without damage. Correct operation is not guaranteed.

The PIC concerned allows Vdd + 0.3V on its pins as an absolute maximum rating. Operation is not guaranteed during this condition.

Most data sheets clearly specify that during normal operation input voltages should not exceed the ground to Vdd range. This datasheet may or may not ro so in its several hundred pages. It is still wrong to do so.

Many people have thought that concerns about protection diode currents are baseless. Only some of them have rued the day they thought so and most have probably lived to rue it or not :-).

Note that the (evil) Atmel application note here uses a 1 megohm resistor (connected to AC mains ! ) and the Microchip app note here - figs 10-1 10-2 at least has the grace to say " ... The current through the clamp diodes should be kept small (in the micro amp range). If the current through the clamping diodes gets too large, then you risk the part latching up." Atmels hundreds of uA is NOT "inh the microamp range".

BUT latch up is the least of your problems. IF you latchup the part (SCR action triggered by currents into IC substrate) the IC often turns into a smoking ruin and you realise that something may possibly be wrong.

The problem with body diode currents is when you do NOT get an immediate smoking ruin. What happens is that the IC was never designed to accept current between input pin and substrate - the layer hat the IC is laid down on. When you raise Vin > Vdd the current effectovely flows out of the ICV proper into a phantom fairyland tyhat the iC is unaware of and that the designer did not and usually cannot design for. Once there you have small potentia;s set up that are never normally there and current can flow back into adjacent circuit modes, of not quite adjacent nodes or even into locations somedistance away depending on how big the currents are and what voltages are set up. The reason this is hard to dscribe and pin down is because it is totally undesigned and essentially undesignable. One effect is to iject currents into floating nodes that have no formal output path. Thse may act as gates for FETs - formal or accidental ones, that tuirn on or off semirandom parts of your circuit. Which parts ? When? How often? How long? How hard? Answer - who can tell / nobody can tell - its undesigned an unesignable.

Q: Does this actually happen? A: Oh yes! Q: Have I seen it happen? A: Yes.

I started what has now proved to be a 1+ decade crusade to make people aware of this (even though I should hav ebeen well aware of it) after being very badly bitten by it.
I had a relatively simple async serial circuit that caused me no end of strife. Processor operation was intermittent or semi random. Code faulted sometimes and not other times. Nothing was stable. The problem? Body diode conduction, of course. I had copied a simple circuit from an application note supplied with a product and away we went.

If you do this without due care it WILL bite you.
If you do it with care and intelligence and design it may well not bite you. But may.
This is akin to pulling over the center line into ongoing traffic to overtake - done with care and not too often and leaving what may be good enough margins you will usually not die. If you do you will probably not be surprised :-). So it is with body diode conduction. Microchips 'microamp range" may be OK. Atmel's 1 megohm off mains is an accident waiting to happen. Suit yourself.

• Russel, I think your concerns are baseless. What I have proposed is not only common practice, it also is recommended by a manufacturer in one of his application notes. See the add-on in my post. – Curd Jan 26 '12 at 11:39
• Russel, please back your warnings by some substantial publications or own experimental data that can be reproduced. Otherwise you're just doing esotericism. – Curd Jan 26 '12 at 13:23
• @Curd - Your response was 30+ minuts after my update so I assume that you either didn't read it, or didn't understand it, or choose to ignore it. As I said (1) I have had this happen (2) By definition it is NOT reproducible with preciseness except in gross cases.(3) You can easily do it yourself. I described my experimental setup well enough for 'one skilled in the art' = async serial receive with body diodes acting as clamps. Results = mayhem. (4) Esotericism's a great word BUT did you understand the undesigned and undesignable aspect and that you MUST violate the spec sheet to do it? – Russell McMahon Jan 26 '12 at 13:33
• First I was stunned by this wall of text, but after I have gone through it, I realy like your answer. It even has some useful background information. Thank you! – PetPaulsen Jan 26 '12 at 13:50
• +1 This needs to bubble to the top especially in contrast to the bad answer from @Curd. – Olin Lathrop Jan 26 '12 at 15:02

Just use an inverter made out of a single transistor and a couple of resistors. Since you are measuring the frequency, it does not matter if the signal is inverted or not - the frequency is the same. You can use a "digital transistor" that has the resistors inside or you can use almost any regular transistor and add the (10K or so) base resistor outside (the one between base and emitter is not mandatory, but you can add it too). I used this circuit to convert voltage from 25Vtop to 5Vtop to measure the AC line frequency.

The easiest way is to clamp the input signal to Vcc (+5V):

The resistor value is not critical, but it shouldn't be too small; maybe in the range 10-100 kOhms.

If you are really picky about the Vcc+0.3V requirement, you should use a Schottky diode; but I think your µC wont be harmed if you use an ordinary 1N4148.

EDIT:
To support my opinion that it is completely save to use this circuit (in contrast to the concerns mentioned in the comments) see following publications on this topic; mainly from IC manufacturers:

Microchip:

chapter 8.pdf, Tip #10, Figures 10-1 and 10-2

Many manufacturers protect their I/O pins from exceeding the maximum allowable voltage specification by using clamping diodes. These clamping diodes keep the pin from going more than a diode drop below VSS and a diode drop above VDD. To use the clamping diode to protect the input, you still need to look at the current through the clamping diode. The current through the clamp diodes should be kept small (in the micro amp range). If the current through the clamping diodes gets too large, then you risk the part latching up.

Atmel:

doc2508.pdf, Figure 1

To protect the device from voltages above VCC and below GND, the AVR has internal clamping diodes on the I/O pins (see Figure 1). The diodes are connected from the pins to VCC and GND and keep all input signals within the AVR’s operating voltage (see Fig- ure 2). Any voltage higher than VCC + 0.5V will be forced down to VCC + 0.5V (0.5V is the voltage drop over the diode) and any voltage below GND - 0.5V will be forced up to GND - 0.5V.
By adding a large resistor in series, these diodes can be used to convert a high voltage sinus signal down to a low voltage square wave signal, with amplitude within the AVR’s operating voltage ± 0.5V. The diodes will thus clamp the high voltage signal down to the AVR’s operating voltage.

Texas Instruments

slya014a.pdf "3.7 External Protection Circuits", Fig. 13

Usually, there is no difficulty in choosing a suitable resistor for the input circuit. Resistor values of 1 kΩ to 10 kΩ usually are appropriate. In practice, it usually is adequate to use only a high-value resistor, without additional diodes.

and even for analog ICs
Analog Devices proposes

EDch 11 overvoltage and emi.pdf

For those amplifiers where external protection is clearly required against both overvoltage abuse and output phase reversal, a common technique is to use a series resistance, Rs, to limit fault current, and Schottky diodes to clamp the input signal to the supplies, as shown in Figure 11.7. The external input series resistance, Rs, will be provided by the manufacturer of the amplifier, or determined empirically by the user with the method previously shown in Figure 11.2 and Eq. 11.1. More often than not, the value of this resistor will provide enough protection against output voltage phase reversal, as well as limiting the fault current through the Schottky diodes.

Maxim

Overvoltage Protection (OVP) for Sensitive Amplifier Applications

An industry rule of thumb is to select RLIMIT so that no more than 5mA will flow through the IC input.

Finally lets see what
Horowitz/Hill "The Art of Electronis" have to say about this topic:

A CMOS input draws no current (...) for input voltages between ground and the supply voltages. For voltages beyond the supply range, the input looks like a pair of clamping diodes to the positive supply and the ground. Momentary currents greater than about 10mA through these diodes is all it takes to put many CMOS devices into SCR latchup (...; newer designs withstand higher currents and tend to be resitant, or immune, to this disease; for example the HC and HCT families can be driven 1.5V beyond the supply rails without malfunction or damage).

EDIT2:
I guess what Russel is so concerned about is the Latch-up effect, that modern ICs are much more resistant agains as in the early days. Maybe that explains somehow his "1+ decade crusade".

EDIT3:
The PIC16F1827 datasheet ("30.0 ELECTRICAL SPECIFICATIONS") says absolute maximum ratings for clamp current Ik is 20mA. That's the current that would damage the chip. The App note proposes a current in the µA range.

EDIT4
I found another app note by Microchip solely dedicated to the issue "Using the ESD Parasitic Diodes on Mixed Signal Microcontrollers".

Is says overvoltage (more than Vdd+0.3V) can cause problems if applied to the pins that can be used as analog inputs.

The first solution is to prevent any overvoltage from appearing on the I/O pins of the microcontroller. This can be done by adding Schottky diodes to VDD and from VSS on each pin that could see a high voltage. This will clamp the voltages to VDD + 0.3V

...just as I suggested from the beginning.

The document also makes clear that it is not true that overvoltage applied to a Microchip controller input results in currents into the substrate (as claimed in the comments). This can only happen at undervoltage (= below Vss; see paragraph "Undervoltage") which is not the topic of this question.

(Those currents into the substrate can not happen at overvoltage and undervoltage because it depends on the doping of the substrate. It is either p- or n-doped, not both at the same time)

• The above is not meant to be an "attack". I appreciate that having one's suggestions criticised is often not pleasant. | You are in good company :-) - MANY MANY people do this sort of thing and defend the practice stubbornly. The fact is that it does violate data sheet specs and it CAN cause unknown hidden problems. It may work OK for hours days weeks months or years. And it may also cause ongoing unknown and untraceable problems. It MUST be "avoided like the plague". | One of my life goals is to educate mankind on this particular problem :-) :-) :-) – Russell McMahon Jan 26 '12 at 10:56
• @Russell McMahon: thank you for your skeptical opinion, but I would appreciate it more if you could provide some substantial justification (e.g. links to publications concerning the issue or own experiments that can be reproduced). – Curd Jan 26 '12 at 11:16
• @Curd: Russell is right. Your circuit would probably work most of the time, but it is not a good idea. At the very least, it should not be recommended without pointing out this issue. A simple fix would be to follow the your output with a voltage divider that brings 5.7V down to 5.0V. – Olin Lathrop Jan 26 '12 at 12:45
• @Olin and Russell: you didn't provide any substantial justification to what you are saying - let alone that manufacturers (e.g. Mircochip, Atmel) recommend in their app notes exactly what I proposed. Please read them before continuing to argue. – Curd Jan 26 '12 at 13:09
• I've seen all kinds of bad design in app notes. Check the real specs, which are in the datasheet. Look at the maximum pin voltage during operation, and you will see that one diode drop above Vdd is too high. I have personally seen problems from a diode clamp exactly like you show. I don't remember the exact PIC, but the A/D readings got messed up when current went thru the high side protection diode of another pin. This stuff is real. – Olin Lathrop Jan 26 '12 at 13:33

Just use a divider and a non-inverting amplifier powered at 5V with at least 3x gain.

So, at 5V you will have again a 5V output, and the same at 15V because it will saturate. Maybe it's better to use a rail-to-rail solution, but it's not completely necessary if you want just to detect edges.

You might want to consider something off-the-shelf, like a RS232 transceiver or receiver. Most will handle up to 25V (since RS232 spec is +/- 25V max) and some even higher voltages, plus you can get ones with 100% isolation to protect your circuit from ground-loops and other bad electrical issues.

Though RS232 is suppose to be +/- voltages, most modern RS232 chips consider a little bit above ground to be the threshold for a negative signal, thus your input should work with them. The reason this must work on RS232 chips is that a lot of bastardized RS232 outputs don't output +/-, but instead are positive signal or ground, thus modern RS232 chips must work with those types of signals. Check each datasheet for the threshold.

The logic-level signals that you get out will be inverted, but this shouldn't be of concern because you are measuring frequency.

+/-50V Isolated, 3.0V to 5.5V, 250kbps, 2 Tx/2 Rx, RS-232 Transceiver: http://www.maxim-ic.com/datasheet/index.mvp/id/3368

Various other RS232 chips: http://www.maxim-ic.com/products/protection/esd/rs232.cfm

• Unless you've already got an unused RS232 transceiver in the circuit, this is not very cost effective. The high-voltage inputs are a tiny part of the silicon you're buying. Pentium100's answer describes an equivalent circuit that's far cheaper and smaller. – Kevin Vermeer Feb 2 '12 at 19:18

You people with special issues with Body diodes or clamping diodes probably didn't have a large enough capacitor across the power supply close to the IC.

The diode is shunting the current to the +supply. If there isn't a big enough capacitor to absorb this it will cause problems. It is just the supply rail getting spiked up. Becuase you are using a rediulously small capacitor (0.1uF ?)

It has nothing to do with any mystery inside the silicon.

Just make sure you have a decent (10uF) cap near the chip Depending on how much current you are putting through the body diode/s.

10mA is fine. It is a diode.

I don't use external protection diodes. I use 2k7 resistors. You can connect 12 volts to the input of a 5V part, no problems. No worries. Try to understand what is actually happening before you start talking about floating fets and injecting currents into fairy land.