Counting, frequency, Jeremy Leach

nbw

Senior Member
This is a frequency counter question after reading Jeremy's neat code in http://www.picaxeforum.co.uk/showthread.php?t=5732&highlight=count+overflow

I'm designing a simple frequency counter for use to 200MHz, most for FM radio work. I've factored in a 1.1GHz MC12080 pre-scaler, and with the use of a second, or a divide-down-thru-5bits chips, can get the signal to a reasonable level where an 8, 16MHz picaxe could easily "count" it. A 64MHz 20X2 would be laughing.

The issue is, of course, the overflow. Only being able to count pulses up to 65535 means a bit of a loss of accuracy. You can shorten the gate, but you lose a bit of accuracy. You can divide down further, but same problem.

I'm trying to get a feeling for whether I could build on Jeremy's code for the 08M to run say, an 18X (vintage / classic!) with the 12080 pre-scalar and something like a 4040 to chop the signal down a bit further.

Aside from driving an LCD say 1x per second, the picaxe would be dedicated to counting. Auto-ranging might be nice but let's not get too fancy just yet! I could use a 4040 as the count coming out of pre-scaler is quite low - 200MHz / 80 = 2.7MHz which is accpetable for the (sluggish) 4040.

ANy advice appreciated. This will be built on a tighter-than-2-coats-of-paint PCB, ground plane on the other side, shielded cable.
 

graynomad

Senior Member
It looks like the MC12080 only has a 1v2 pp output, you'll have to condition that.

The 4040 doesn't have a method of holding the count, so it would be best to gate the clock while reading.

You'll need 3 + 12 pins (+ 1 if you gate the clock) so the 18M2 should just scrape in unless you have other stuff to control.

OR (this is probably what you meant, I'm a bit slow :))

Are you going to use it as another prescaler, in which case you only need 1 pin. If you use the 4040's Q12 output you could time the period for 610 secs I think which would be very accurate, or choose another Q to trade off accuracy for response time.
 
Last edited:

nbw

Senior Member
I was wondering about that. I thought by controlling the period on the picaxe's "count" command, that would effectively act as a gate of sorts. The main issue is dealing with the 16-bit 65535 count, taking 2 separate readings from different parts of the 4040 output would work, with some conversion by the picaxe. However, you'd need to do both counts at the same time, which I'm not sure the picaxe can do?

cheers
 

graynomad

Senior Member
I'm sure a Picaxe guru will step in shortly, but meanwhile...

The count command would work I think, set the gate time for something you are happy with as far as response time is concerned, then pick a 4040 Q output that gives you a high enough reading to have the resolution you want.

If you crank the Picaxe up to 8MHz (I gather you can do that) you can count at 50KHz.

200,000,000 / 80 / 2^6 is about 39KHz so if you count pulses on Q6 (or is it 7?) for 1/2 a second you'll stay within the 16k limit of the counter and get pretty good resolution, at least at the higher frequencies. And by connecting several Q outputs to the Picaxe you can auto range by "count"ing on different pins.

You can juggle the Q used and the gate time to get the count as high as possible without crossing the 65k limit.

How to auto range? I reckon that say if you're counting on Qn you set an interrupt on Qn+1, if you get the interrupt you have to move up to the next Q, ie count on Qn+1 and interrupt on Qn+2 etc. At the other end, if the count is too small move down a Q.
 
Last edited:

nbw

Senior Member
I was hoping to get 6 digits of resolution at first. e.g. 108.267 MHz is a useful enough precision, as is 2.12345 MHz. That of course tips over the 65,535. I had a (semi) cunning plan at first to count and if it overflowed, use another Q to work out whether it was say 20,000 (no overflow) or 85,535 (1 overflow).

Will have to crunch some numbers for sure.

Possibly a simple voltage amplification and jiggery-pokery set-up post-12080 to get the 1.2Vp2p up to 0-5VDC for the picaxe to handle.
 

graynomad

Senior Member
Let's say then that you're timing Qn and have Qn+1 and Qn+2 (or more)running to Picaxe inputs. At the end of your gate time you read the extra Q bits, multiply that number by 65k and add the count.

You could easily get a count of 6 digits that way but it might take some time, possibly a few seconds. Looking at the fastest speed,

At 200MHz we're counting at say 40kHz and want a count of 200000, 200000/40000 = 5 seconds. Is that right or am I a DP out somewhere?

Also having a count of 6 digits doesn't necessarily mean 6-digits accuracy. The latency in the count function may affect things a small amount although this would not change and therefore be able to be accounted for.

Is the 1v2 pp 0-1v2 or does it have an offset. If it's 0-1v2 it will probably drive a transistor and that can turn it into 0-5v.
 
Last edited:

nbw

Senior Member
Hi Rob, I see what you mean. 200 MHz is the upper limit, realistically the FM band I'll be examining is 88 to 108. If it updated every second or so that would be handy - I have a 20x2 in the shed, which might be put to good use here. At max 400kHz counting speed - even 100kHz, it should run like a cut cat.

Thinking about the 4040 Qs, I might need to just look at the last 8-9 (Q5 - Q14 say) to get a fairly good picture of what's happening. The picaxe would be updating an LCD with the results, but's about it. i.e. quick autorange check > Count > display > quick autorange check > count > display.

Would also need to be able to reset the 4040 from the picaxe, of course.

I'll check that 12080. Yes - a nice 0-1.2V would be simplest, a little transistor would scale it up nicely. Even if it was the other case, the transistor would only switch on 50% of the time, so provided I multiplied the count by 2....

This is going to be fun!!
 

nbw

Senior Member
Another quick thought - by controlling the 3-bits on the MC12080 that set the x10 - x80 factor, I could reduce the scale-down if I was counting less than, say, 1 MHz for whatever reason, without having to extend the count time. Depends of course on how many spare I/O pins I have lying around on the picaxe! Crumbs, or I could get the 20x2 to simply hand off a value to a little brother 18x to write out to an LCD at it's leisure :)
 

Jeremy Leach

Senior Member
That code I wrote was 4 years ago, so I've had to remind myself !

In case there's any misunderstanding, although there were 4 connections between the 4040 and the PICAXE, only one 4040 output was automatically selected, and the Count command used on that output. So all the code did was:
1. Select appropriate 4040 output
2. Use Count command on that output to determine frequency
3. Display frequency

So it tried to maximise accuracy by selecting the 'best' pin, working with the limitations of 65535 counts etc.

The same principle could be used with any ripple counter and any number of pins. So perhaps just go for a bigger PICAXE (ideally with crystal) and then make more connections to the ripple counter. Then extend the code so it selects the 'best' pin to sample, from say 8 pins !

I don't think it should be too hard to do. Autorangeing might get pretty complex, but I'd have thought it's still do-able.
 

nbw

Senior Member
Also take a look at - http://www.picaxeforum.co.uk/showthread.php?t=14517

That uses the internal 'hardware timer' as a counter so can run faster than COUNT.
Hi there Hippy, I wondered if there might have been a snappier way to do the counting. 'count' seemed pretty convenient. Your timer code would be so quick I might not even need (possibly) the 4040 divider!

The big thing for me now is how to get 6 or 7 digits to appear in the picaxe, bearing in mind the 65535 limit. Juggling the Q's and some maths, perhaps. It would be good to have, e.g. 1081234 appear in the picaxe representing 108.1234 MHz. Perhaps, 1 digit in variables b0 - b6, something like that.
 

nbw

Senior Member
That code I wrote was 4 years ago, so I've had to remind myself !

In case there's any misunderstanding, although there were 4 connections between the 4040 and the PICAXE, only one 4040 output was automatically selected, and the Count command used on that output. So all the code did was:
1. Select appropriate 4040 output
2. Use Count command on that output to determine frequency
3. Display frequency

So it tried to maximise accuracy by selecting the 'best' pin, working with the limitations of 65535 counts etc.

The same principle could be used with any ripple counter and any number of pins. So perhaps just go for a bigger PICAXE (ideally with crystal) and then make more connections to the ripple counter. Then extend the code so it selects the 'best' pin to sample, from say 8 pins !

I don't think it should be too hard to do. Autorangeing might get pretty complex, but I'd have thought it's still do-able.

Hi Jeremy, I can see how I can get the 5 digits e.g. 65.535 MHz, but am missing how I can get to 6 or 7 digits - an extra 1 or 2 on top of that. I thought some of your tricky 32-bit maths might be part of the answer.

I've decided to go with a 20x2 - at 64MHz it should run like a cut chook and be fast enough to handle whatever the 4040 (or not, if Hippy's timer is fast enough) can throw at it.
 

nbw

Senior Member
Hi Hippy, I'm trying to digest your whizzy counter code above at the moment. Pretty clever! It's late here, but from what I've seen, it's got possibilities for my freq. counter. Mind you, I still would need a means of counting those pulses. Maybe start the timer, start the 4040, as soon as the 4040 overflows into a certain output, stop your accurate timer and perform some maths from there?
 

Jeremy Leach

Senior Member
Ah, I see the problem now.

I can't think of a way to easily get 7 digits of resolution just using normal Count command.

Maybe the Timer can be used in external count mode, because I think that can also generate an interrupt where you can keep track of the overflows, but I thought it didn't operate well when there was a high frequency of interrupts.
 

nbw

Senior Member
I kind of wondered if I could do a super-fast count (say over 50 ms) to get a double-word to 'grab' the first four digits, then a second count straight after further down the 4040-Q-chain to get the lower four digits. Although 2 counts, if I could do all of that in 1/2 a second or less, I might get the 7-ish digits.....
 

graynomad

Senior Member
It doesn't really matter if you count fast or slow, the principle's the same, just the Q number and the gate time changes.

You count as fast as you can and let the higher Q numbers accumulate the overflow. When the gate closes look at the higher Q numbers, multiply the value on them by the overflow count of your fast counter (normally 256 or 65k), add the value of the fast counter, multiply the result by the gate time and I'm pretty sure that's it.

For any given resolution, if the count freq is slow then you need a long gate time, is it's fast you can have a shorter gate time. I don't think there's any way around that.

Crumbs, or I could get the 20x2 to simply hand off a value to a little brother 18x to write out to an LCD at it's leisure
Nothing wrong with doing that, but I don't think it will be required. As (presumably) the information is for human eyes only you can

Read_Freq
Write_Ddisplay

It doesn't matter if there's time between the calls to Read_Freq.
 
Last edited:

Jeremy Leach

Senior Member
You could call mutiple count instructions and make an estimate of missed counts.

To get 7 digit resolution you need to call roughly 100 count instructions...
Code:
For Iterations = 1 to 100
    Count pin,period, CountValue
    Save the count value, or add it onto a running total 32 bit variable
Next
IF you know the precise execution time of the code between each Count command, then you could make a good estimate of the number of missed counts. If this time period for executing the other code is relatively small then the accuracy perhaps wouldn't be effected too much. So perhaps just poke the CountValues somewhere and nothing else. Then add them up later.

It's just a vague idea, but might be possible. Obviously not ideal.
Also, the Count period would need to be pretty small. Maybe a hundreth of a second so your overall Sample period would be roughly 1 second.
 

hippy

Technical Support
Staff member
Hi Hippy, I'm trying to digest your whizzy counter code above at the moment ... Mind you, I still would need a means of counting those pulses. Maybe start the timer, start the 4040, as soon as the 4040 overflows into a certain output, stop your accurate timer and perform some maths from there?
Most of that code could be binned because you are not interested in time, but only number of pulses. Enable a gate for a certain time, count the number of pulses which arrive. On each overflow of the 16-bit counter increment a separate word register for overflows. Then it's a question of displaying a 32-bit number as decimal ( the code's on the forum somewhere ).

The timer has a max frequency ( would have to look at the data sheet ) so you'd still have to divide then multiply in software, and also if you weren't measuring for a whole second.

It would be better to use a 28X2 which can use a crystal.
 

techElder

Well-known member
... I'm designing a simple frequency counter for use to 200MHz, most for FM radio work.... ... realistically the FM band I'll be examining is 88 to 108....
From the frequencies that you are mentioning, this sounds like our FM broadcast band.

With regard to resolution, this band is divided into 100 KHz "channels", so EVERY frequency doesn't need to be displayed.
 

nbw

Senior Member
It would be pretty nice to be able to break down the freq beyond 100KHz lots, but I understand your point about the FM. When I drop to lower values, like 1 MHz or less, it would be good to keep some resolution in there.
 

nbw

Senior Member
Most of that code could be binned because you are not interested in time, but only number of pulses. Enable a gate for a certain time, count the number of pulses which arrive. On each overflow of the 16-bit counter increment a separate word register for overflows. Then it's a question of displaying a 32-bit number as decimal ( the code's on the forum somewhere ).

The timer has a max frequency ( would have to look at the data sheet ) so you'd still have to divide then multiply in software, and also if you weren't measuring for a whole second.

It would be better to use a 28X2 which can use a crystal.
OK I'll examine that a bit more. That's def. pretty much what I need: gate open, count, gate close, convert to "displayable" 32-bit number. I see the 28x2 can be ramped up to 40 MHz with an external crystal which is quite quick. I have a 40x2 kicking around in the shed from memory, so it might be worth bolting it on to the back end of the pre-scaler when it arrives, for a bit of a play.
 

nbw

Senior Member
Right, I'm going to try a combo of a pre-scaler, some of Hippy's code, a 40X2 with a crystal (32MHz perhaps), and some of the famous J Leach (tm) 32-bit maths.

If I get a bit lost in the code or maths, I'll kindly ask gents Hippy and Jeremy for help :)

Any other advice or tips for the circuitry is appreciated.

So far:
(obvious things like...)

1. 0.1uF decoupling caps near ICs
2. back-to-back high speed signal diodes (1n4148) after the input signal, and pre- the pre-scaler
3. copper traces as wide as possible in the signal path
4. signal path away from power traces
5. no ground loop, but ground plane as much as possible
6. all ground connections to a star point
7. shielded cable from BNC connector to pcb
8. ICs etc as close together as possible
9. fully regulated power supply
10. (overkill?) a grounded, metal cage around the circuitry
 

John West

Senior Member
It would be pretty nice to be able to break down the freq beyond 100KHz lots, but I understand your point about the FM. When I drop to lower values, like 1 MHz or less, it would be good to keep some resolution in there.
Most counters bypass the prescaler at low frequencies.

In addition to the back to back diodes - do you have an input current limiter resistor in front of them?

50 Ohm input impedance matching?

Counter front-ends are often neglected in homebrew counters and that tends to reduce the accuracy and usefulness of them.
 

nbw

Senior Member
Hi John. Yes - I'll have some form of current limiting up front.

I was thinking of driving the prescaler configuration via the picaxe so I could control whether it scaled down by 10, 20, 40, or 80x. I could take a quick sample using the scaler at 80x and then if the resulting count is too low suggesting a lower frequency, drop the pre-scaling to 10x and read that. With a 32MHz crystal, my picaxe should be able to count up to 200kHz, so using 10x, any signal 2MHz and under could go through this path.

I'll have to learn about impedance matching. I've heard of it, but don't know any more about it in the context of freq counters.
 

eclectic

Moderator
Hi John. Yes - I'll have some form of current limiting up front.

I was thinking of driving the prescaler configuration via the picaxe so I could control whether it scaled down by 10, 20, 40, or 80x. I could take a quick sample using the scaler at 80x and then if the resulting count is too low suggesting a lower frequency, drop the pre-scaling to 10x and read that. With a 32MHz crystal, my picaxe should be able to count up to 200kHz, so using 10x, any signal 2MHz and under could go through this path.

I'll have to learn about impedance matching. I've heard of it, but don't know any more about it in the context of freq counters.
Just a small, but important point.
Manual 2, p.208.
"Note that the X2parts have an internal x4 PLL inside the chip. This multiplies the
external resonator speed by 4. Therefore the external resonator value to be used
is 1/4 of the desired final speed (ie in mode em40 use an external 10MHz
resonator, for em16 use a 4MHz resonator)."


And, if you use the 3v version, you can go even faster! :)
e
 

nbw

Senior Member
Crumbs yes, good point. A 10MHz resonator then is the ticket. May as well as run that little beast as quick as possible.

My manuals must be out of date... my Man2, p208 is talking about "bpm". I'll have a look around that area though. I can't see any reason why I shouldn't use a 3V picaxe in this counter. The faster the better, right??!
 

eclectic

Moderator
Crumbs yes, good point. A 10MHz resonator then is the ticket. May as well as run that little beast as quick as possible.

My manuals must be out of date... my Man2, p208 is talking about "bpm". I'll have a look around that area though. I can't see any reason why I shouldn't use a 3V picaxe in this counter. The faster the better, right??!
In that case, download the latest version of P.E. asap! :)

e
 

Jeremy Leach

Senior Member
Ok I have a question, maybe for Hippy:

Using the SetTimer command and using the External counter mode, can the internal counter register be Peeked in any way? The manual says not, but I'm just checking :).

If it could, then this register and the Timer variable would be a useful 32 bit counter variable.
 

nbw

Senior Member
Hey, here's a thought. The 18M2 can run 4 programs at the same time. Maybe I could have a 4040 downstream from the pre-scaler, then have 4 different outputs from that being counted by four program streams in the 18M2. That way, one output could count the high end e.g. MHz, an output further downstream could count the kHz etc. By experimenting with the period in the count command, it may simply the maths considerably.

By running the 18M2 at full whack (32MHz) and using 4 simultaneous flows, I might just be able to get that magical 7 digits resolution!
 

hippy

Technical Support
Staff member
On 64MHz ( 4 x 16MHz ) isn't that for the X2-3V only, the X2-5V have 40MHz max ? I don't know if anyone has tried over-clocking but recall some impressive reports of success on some.

On SetTimer, not sure where it says the timer / counter cannot ( or in what context ) be peeked but I'd have expected it could be. If not, just use SFR's to to set it as required rather than use SetTimer.

On 18M2, I don't think you'd get any benefit from trying to count things in separate tasks.

And finally, on PICAXE execution speed; is it actually important ? AIUI, the hardware counter increments at whatever rate the input pulses appear regardless of how slowly the PICmicro / PICAXE is pootling along or the oscillator speed. The only requirement being fast enough that any overflows of the counter aren't missed. That will be happening every 65536 pulses.
 

nbw

Senior Member
Yes - only the 3V versions can run at 64.

My understanding of SFRs etc is ashamedly low... reading required there. The main thing about the execution speed was the faster it is, the higher the kHz range I can 'count' at. 4MHz is limited to 25kHz I think, so even the little 18m2 at 32MHz could read at 200 kHz. I could take smaller snapshots to count the same frequency, for what that's worth. Or, get more resolution through a longer 4040 read for the same counting period, I guess.

If I was a teenager, I could slap a Peltier module on to super-cool it, a few LEDs to bling up the PCB etc LOL.
 

hippy

Technical Support
Staff member
4MHz is limited to 25kHz

I think you're confusing the software COUNT command with the hardware counter, but I must admit that I haven't read all the thread in detail. Too tired at the moment to fully decode the datasheet but Table 26-11 seems to indicate a counting rate in excess of 10MHz.
 

nbw

Senior Member
I reckon, it must be nearly 1am there in sunny England.

Yes - I've only dealt with the software Count, never been near a hardware counter. Not even sure which table you refer to... but it's probably a microchip doc or similar?

cheers
Barney
 

Jeremy Leach

Senior Member
The Manual says :
settimer
Syntax:
SETTIMER OFF
SETTIMER preload
SETTIMER COUNT preload
...
...
External Counter (not available on 20X2)
In external counter mode an internal counter register (not accessible to the end
user) is incremented on every positive going edge detected on input 0. This pulse
counting occurs in the background, so the PICAXE program can perform other
tasks at the same time as it is counting (unlike the count command, which stops
other processing during the count command time period). When the internal
counter register overflows from 65535 to 0, the special ‘timer’ variable is

automatically incremented.
 

hippy

Technical Support
Staff member
Thanks Jeremy. By "not accessible" I would take it as meaning that the counter is not accessible or usable by any easy means such as through any potential READCOUNTER command, that is the Basic Language doesn't make it explicitly accessible.
 

Jeremy Leach

Senior Member
Well if it's peekable (address?) then I think this could potentially be very useful for accurately measuring frequency , because the peeked counter value (Word) and the Timer variable (Word) both make a 32 bit counter. Which could give > 7 digits of resolution on frequency measurements.

The Timer variable can raise an interrupt on overflow which means that the overall counter variable could even be > 32 bits.

You need the low level counter value for the accuracy.
 

nbw

Senior Member
Crumbs that would be the business if it was readable. I wonder if you can kind of add it to another readable variable or address, then work out by deducing what the timer overflow was?
 

hippy

Technical Support
Staff member
Using PEEK or PEEKSFR most/many addresses within a PICAXE are readable. While Rev-Ed support the commands we do not support specific uses of the commands, do not guarantee that what you'd like to do will be possible, will work, will always work. Cannot offer full and official support for all possible things end-users may wish to achieve that way.

It's a bit like car tweaking; manufacturers won't officially sanction squirting toothpaste into the fuel tank if that is claimed to improve performance. Working out which toothpaste, how much to use, taking the risk of it working or not, is on the head of those wanting to try it.
 

Jeremy Leach

Senior Member
I think perhaps Rev-Ed should have some stickys with these disclaimers (including PICAXEs used in mains projects, in cars etc etc) and these can be referred to as necessary.

It would be nice if some of these PEEKable addresses were published too, so people can experiment (knowing that discaimer x applies). I'm sure it's all in the low level datasheets for the PICs but I don't see the problem in making the info available (apologies if it's already in the manual somewhere).

For instance, IF reading the low-level counter is PEEKable then it might be useful to people.
 
Top