Author Topic: Measuring time span very precise  (Read 8295 times)

0 Members and 1 Guest are viewing this topic.

Offline HendriXMLTopic starter

  • Super Contributor
  • ***
  • Posts: 1085
  • Country: nl
    • KiCad-BOM-reporter
Measuring time span very precise
« on: September 06, 2019, 10:46:32 pm »
From the project below I get two digital signals from laser GateA and GateB I would like to determine the time between them.
Nerfo meter - measuring the speed of Nerf darts

The timing circuit will be reused in other experiments and needs to be readable by an Arduino Mega2560.

I came up with the following:

Why not use the 74LV8154 to count ticks in 32 bit mode. At the GateA signal the counter is saved to its registers. At the same time the Arduino is triggered/interrupted to read this data. This is allowed to take 100 us. The same will happen when the GateB signal fires.

The ticks will be at around 1 Mhz. Thus allowing for 1 hour of high precision timing. But if I where to generate the ticks with a M74HC4060 (oscillator/14 stage binary counter), I could also use a divider output of 16x or 32x etc. This will mean running that IC on about 16 Mhz. Which would mean it could run for 50 days using the greatest divider (off course with a lowered resolution).

Is there a way to use an special purpose IC to hook the counter IC to a by a software chosen divider pin? Or is this a case where AND gate's would be needed? (I could also use jumpers, losing software capabilities...)

If the Arduino reads the counter registers too slow, the circuit is limited by how small the time span between GateA and GateB might be. To solve this 2 synchronous counters (2x 74LV8154) could be used, clocking and starting them at the same time. But that seems like a uneconomical solution.

This seems to me like it could work, but any thoughts or suggestions are appreciated!

« Last Edit: September 06, 2019, 11:29:28 pm by HendriXML »
“I ‘d like to reincarnate as a dung beetle, ‘cause there’s nothing wrong with a shitty life, real misery comes from high expectations”
 

Offline HendriXMLTopic starter

  • Super Contributor
  • ***
  • Posts: 1085
  • Country: nl
    • KiCad-BOM-reporter
Re: Measuring time span very precise
« Reply #1 on: September 06, 2019, 11:52:00 pm »
I think that doing a counter clear on the GateA signal would be the most easy solution to keep the minimal timespan short. This way the registers will not need to be read during the 2 events.  :popcorn:
“I ‘d like to reincarnate as a dung beetle, ‘cause there’s nothing wrong with a shitty life, real misery comes from high expectations”
 

Offline hamster_nz

  • Super Contributor
  • ***
  • Posts: 2812
  • Country: nz
Re: Measuring time span very precise
« Reply #2 on: September 07, 2019, 12:12:27 am »
Simple, accurate, and cheap. Borrow an FPGA dev board
Gaze not into the abyss, lest you become recognized as an abyss domain expert, and they expect you keep gazing into the damn thing.
 

Offline DaJMasta

  • Super Contributor
  • ***
  • Posts: 2393
  • Country: us
    • medpants.com
Re: Measuring time span very precise
« Reply #3 on: September 07, 2019, 12:16:56 am »
You can probably get good results with a hardware interrupt for the end pulse edge and a software start, but if you want really fast, why not a hardware counter?

Whatever timebase you want piped into an AND gate to control when it runs and then into the clock input of a counter like a 74 series 4040.  Micro turns on the other and gate input to enable the clock, counter runs, ending trigger pulse either goes into the AND as well, or pulls down the micro's control line, or through another mechanism to stop it.  Micro reads the 12 bits of output from the counter, then triggers the reset line, then you wait until you want to time another.

If you don't have the micro controlling the start, you can have the first laser trigger a latch (like a D flip flop), then have the second laser trigger a second latch.  Have the normal output of the first latch start the AND gate and the inverted output of the second latch enter the AND gate as well to stop it.  If you reset between laser trigger pulses, that should give you the 12 bits of counting for each counter.  If you run your counter's clock from a 1MHz or 10MHz crystal oscillator, it should be pretty accurate and stable and you'll get a 1us/100ns resolution on your reading.


The problem with the 14 bit is that the two least significant bits aren't broken out in the standard pinout.  Cascading counters works great, and at 1MHz especially, 24 bits of counting gives you a maximum of over 16s of delay that can be measured at 1us.
« Last Edit: September 07, 2019, 12:18:47 am by DaJMasta »
 

Offline IDEngineer

  • Super Contributor
  • ***
  • Posts: 1950
  • Country: us
Re: Measuring time span very precise
« Reply #4 on: September 07, 2019, 04:55:24 am »
How about a small MCU? Many are available with relatively low pin counts and small packages, and you'd have more flexibility than any dedicated IC.

I happen to have a PIC18F spec sheet sitting here. At quick glance, it has direct support for cascading eight and 16 bit timers to form a 24 bit counter that can be clocked by anything from the main oscillator (62.5nS resolution) on up to a bunch of intervals that are selectable via prescalers. That's a counting range of 16M, and at 62.5nS resolution that's a run time of one second. You can obviously scale resolution to lengthen the max time period.

Still not enough? With a single pin-to-pin connection you could cascade two 16 bit timers. Now you're at 4G counts, which at the highest resolution gives you 268 seconds. I suspect you could cascade two of the 8+16 arrangements to get up to 48 bits, again with a single pin-to-pin connection. That would give you 203 DAYS of counting before overflow at 62.5nS resolution.

As for reading/writing, MCU's (including this one) have all sorts of communications peripherals on chip. This one has SPI, I2C, UART, etc. and you could bit-bang your own if necessary (nybble-wide bus, anyone?). Personally I'd go for SPI if the Arduino supports it since you cannot get out of phase and the bit rates are probably several megahertz, but even a serial link would probably be fast enough for what you want to do. Again, all on chip, ready to go, and reconfigurable with a reflash as you gain experience and redesign things.

Just something to consider. Small MCU's are often a great alternative to one or more dedicated devices.

Edit: Oh yeah, forgot to mention that MCU timer/counters generally have several hardware pin options. You can externally clock them, gate them for easy start/stop, they can emit a level or pulse upon match with an internal preset register... all of which would ease your interfacing. This one even has gating based on an on-chip analog comparator so you could trigger based on a non-digital-friendly voltage threshold.
« Last Edit: September 07, 2019, 04:57:17 am by IDEngineer »
 

Offline Rerouter

  • Super Contributor
  • ***
  • Posts: 4705
  • Country: au
  • Question Everything... Except This Statement
Re: Measuring time span very precise
« Reply #5 on: September 07, 2019, 05:17:08 am »
Best of both worlds, just have 2 cheap micros running off the same clock, with reset lines tied together. have them both use analog comparator hardware to capture the time of a pin change, they just count the overflow timers and save the timer capture registers when they fire, have the chip that measured a trigger assert some interrupt pin low, the mega reads it off by SPI, and away you go.

The gets you the timing resolution of up to your external clock / 2, a total duration of up to 400 days if you use a 32 bit register to count the overflows, and allows you to set arbitrary trigger voltages within its supply range.
 

Online magic

  • Super Contributor
  • ***
  • Posts: 7453
  • Country: pl
Re: Measuring time span very precise
« Reply #6 on: September 07, 2019, 05:43:55 am »
Easily a job for one AVR micro. Probably other families could do it too.

Use the "input capture" function of the hardware counters. It counts cycles of the system clock (optionally divided by 2,4,...) and stores the current count in a side register when a specific input pin changes state. Then an interrupt is fired and you can process the event; simply copying this register to RAM will take a few µs at most.

Counter overflow can also trigger an interrupt, so a 16 bit counter can be extended to 32 bits by software.

You don't need 64bit timers to run for a long time. When you see that timeB < timeA you can know that the real time was INT_MAX-timeA+timeB. The only catch is, if the counter overflows every second, you won't be able to tell apart 1ms from 1ms+1s or 1ms+2s and so on. But you don't need to write software which craps out when the counter overflows after a year of continuous operation.
 
The following users thanked this post: Kilrah, nugglix

Offline FenTiger

  • Regular Contributor
  • *
  • Posts: 88
  • Country: gb
Re: Measuring time span very precise
« Reply #7 on: September 07, 2019, 05:50:32 am »
needs to be readable by an Arduino Mega2560

What resolution do you need?

This seems like a reasonably good fit, if you can find a 10MHz reference for it: https://www.tapr.org/kits_ticc.html

 

Offline Ian.M

  • Super Contributor
  • ***
  • Posts: 13216
Re: Measuring time span very precise
« Reply #8 on: September 07, 2019, 06:51:38 am »
See the ATmega2560 datasheet section 18.4.1 GTCCR - General Timer/Counter Control Register, Bit 7 – TSM: Timer/Counter Synchronization Mode.  Using it, multiple Arduino Mega2560 16 bit timers can be initialised to run in lock-step with each other.  Then you can use separate input capture units to timestamp your start and stop external events and calculate the interval as Magic suggests in reply 6 above, even if the events are only a single ATmega clock cycle apart.  Assuming the counter and captures are extended in software to 32 bit, at the highest resolution of 1/16 us, you get a rollover period of a bit under five minutes.  Drop the resolution to 1/2 using the prescaler and the rollover interval becomes slightly under 36 minutes.  The next step down has a resolution of 4us and a rollover period of 4 3/4 hours.

The only fly in the ointment is the poor accuracy of the typical Arduino ceramic resonator clock oscillator, so you will probably need to feed the Arduino a master clock from a much better quality oscillator.
 

Online Kleinstein

  • Super Contributor
  • ***
  • Posts: 15153
  • Country: de
Re: Measuring time span very precise
« Reply #9 on: September 07, 2019, 07:11:55 am »
The mega2560 or other µC in the Arduino can do the timing with the input capture function. So no extra hardware is needed. One can even use the analog comparator as the trigger source and route the signal from the ADC inputs. So one can use different inputs for start and stop, if there is some minimum time (some 1-5 µs) to switch the trigger source.

It is possible to extend the resolution in software to 32 Bit, or if needed also 48 bits. So there is no real need to use a pre-scaler for the clock.  However there is a tricky point when counter overflow and capture event happen at the same time. This difficulty can be solved, but it needs some extra thoughts or searching for an existing solution.
 

Online magic

  • Super Contributor
  • ***
  • Posts: 7453
  • Country: pl
Re: Measuring time span very precise
« Reply #10 on: September 07, 2019, 09:01:35 am »
Mega2560 is a big part so it probably has multiple counters with input capture on different pins, in which case no switching is even needed.

However there is a tricky point when counter overflow and capture event happen at the same time. This difficulty can be solved, but it needs some extra thoughts or searching for an existing solution.
Good observation.

If I'm reading the docs correctly, a lower numbered interrupt has higher priority, so input capture IRQ should be executed before overflow IRQ if they occur in the same clock cycle. Probably the simplest way to deal with it is to check if the captured timestamp is zero and then execute the overflow IRQ handler and clear the overflow IRQ flag before proceeding further.

edit
Or not. Better check the overflow flag.
Interrupts may be disabled when an overflow happens and then an event may be captured at count=1 and yet the capture IRQ will be executed before the overflow IRQ when interrupts are unblocked.
« Last Edit: September 07, 2019, 09:08:07 am by magic »
 

Online Kleinstein

  • Super Contributor
  • ***
  • Posts: 15153
  • Country: de
Re: Measuring time span very precise
« Reply #11 on: September 07, 2019, 09:22:21 am »
The interrupt priorities do not fully help to solve the possible race condition, as it applies to the interrupt waiting in the queue. There still is a possibility that the capture interrupt is executes before an overflow interrupt.

The way to check for the race condition is to check the interrupt flag for the overflow inside the ICP ISR.  The value of the captured time stamp tells if a possible pending overflow interrupt should have come before ( small capture value) or after the capture event ( large capture value).

A suitable program can be found here (text in German):
https://rn-wissen.de/wiki/index.php/Timer/Counter_(Avr)#Input_Capture
 
The following users thanked this post: Ian.M

Offline HendriXMLTopic starter

  • Super Contributor
  • ***
  • Posts: 1085
  • Country: nl
    • KiCad-BOM-reporter
Re: Measuring time span very precise
« Reply #12 on: September 07, 2019, 10:20:06 am »
Thanks for all the comprehensive suggestions! I'll investigate them.

Initially the idea was to use a prefab Arduino with a not so great oscillator. I could try to replace it with a good spec one. I've used them Mega2560 timers controlling a steppers using an acceleration table (instead of linear acceleration) which took loss off torque in higher RPM's into account. I also did a fun project to have 15 rbg leds be driven using color event tables which where created for supporting "thunderstruck by AC/DC".
If there's a possibility to reset their counter without software interference then that would be neat, I'll have to try to figure that out.
If interrupts are needed for starting and stopping then I would probably leave this road, not because it would not do the current job well. But mainly because off my the goals I've set to minimize the delays to less that a usec. I'd also like to use electronic components to build up experience with them, instead of the more know territory. (I haven't created a digital circuit yet)
I'm now short in time, but will respond more later on.
Thanks to you all!
“I ‘d like to reincarnate as a dung beetle, ‘cause there’s nothing wrong with a shitty life, real misery comes from high expectations”
 

Online Kleinstein

  • Super Contributor
  • ***
  • Posts: 15153
  • Country: de
Re: Measuring time span very precise
« Reply #13 on: September 07, 2019, 10:59:57 am »
There are likely interrupts used for the control at start and stop and if needed also the extension of the resolution. However the actual timing is done by the timer hardware. So the accuracy is as good as the clock with clock cycle resolution.
The trick is not to reset the timer, but already have the timer running and use time stamps at the start and end.
 
The following users thanked this post: Kilrah

Online magic

  • Super Contributor
  • ***
  • Posts: 7453
  • Country: pl
Re: Measuring time span very precise
« Reply #14 on: September 07, 2019, 11:02:50 am »
If your MCU has two timers with separate input capture pins, events A and B can be captured by separate timers.
In such case they may be spaced even 1 clock cycle apart, which is 1/16µs at 16MHz.
The software will then read timestamps captured by each counter and calculate the difference.

edit
Basically, we are trying to convince you that all the digital logic hardware you described in the original post is already in your MCU, just use it :)
« Last Edit: September 07, 2019, 11:07:57 am by magic »
 
The following users thanked this post: Kilrah

Online iMo

  • Super Contributor
  • ***
  • Posts: 5570
  • Country: va
Re: Measuring time span very precise
« Reply #15 on: September 07, 2019, 11:20:38 am »
TDC7200, easy to use, libs for arduino..

PS: with that chip (works fine) you may upgrade from the nerf darts gun to a railgun later on.. :D
« Last Edit: September 07, 2019, 11:44:11 am by imo »
Readers discretion is advised..
 
The following users thanked this post: Kilrah

Offline max_torque

  • Super Contributor
  • ***
  • Posts: 1327
  • Country: gb
    • bitdynamics
Re: Measuring time span very precise
« Reply #16 on: September 07, 2019, 02:03:08 pm »
define precise?

I recently did a project with a 32b counter ic, driven by an over stabilised oscillator at 40Mhz, and a micro just uploads the counts when it's triggers, and takes one for the other (as mentioned previously) to get the counts difference.  The oscillator was calibrated using a GPSDO, so i've got 25ns resolution.   At that level you have to be really carefully of your triggering jitter and latency, matching your triggers so as to not create an offset to the "true" events!

even for a flight time measured in ms, your resolution looks good  (10ms = 40,000 counts!)
 

Offline Ian.M

  • Super Contributor
  • ***
  • Posts: 13216
Re: Measuring time span very precise
« Reply #17 on: September 07, 2019, 02:25:29 pm »
There's not much fun and learning in using a single chip time of flight event timer breakout  board + 'canned' Arduino libraries.  If we want to do it the smart hard way (but not the hard hard way, which would be a board full of individual counter chips, or the lazy way which would be throw a FPGA at the problem), you have to understand the constraints on a practical solution.

Lets put some numbers on the problem.  A M61 Vulcan rotary cannon, has a published muzzle velocity of 1050 m/s.   Assuming a 10MHz counter clock, you'll get fractionally under 10 counts for every mm the round travels.  Nerf guns in the Rival series allegedly top out at around 30 m/s (other series are around half that), so with the same 10MHz counter clock, you'll get 333 counts per mm of round travel.   For comparison, a good fastball bowler is about as fast as the Nerf Rival dart.

At 10MHz input clock, a 16 bit counter rolls over in slightly over 6.55 ms, 24 bit in slightly under 1.68 seconds, and 32 bit in slightly over 7 minutes 10 seconds.

That means that with 100mm between sensors slower Nerf darts will probably  overflow a 16 bit timer clocked at 10MHz overflow a 16 bit counter clocked at 10MHz.  Put the sensors further apart or use the Arduino 16MHz resonator and you'll definitely overflow the AVR 16 bit timer 1 if you don't use the prescaler to drop the timer clock to 1MHz. 

Some MCUs are much better than others for high clock speed counting.  e.g. the AVRs used in 8 bit Arduino boards synchronise the external counter clock to the core clock, so with a 16Mhz resonator, the maximum input frequency is fractionally under 8MHz with an exact 50% duty cycle. 

PIC18 series chips generally do much better as they have an asynchronous up to 8 bit prescaler for timer 0 followed by a synchronous 16 bit timer, and the prescaler can be clocked at up to 50MHz, (50% duty cycle again) as long as you meet the constraint FT0CKI<N/(4/Fosc + 40ns), where N is the prescaler ratio.   
At even 1MHz Fosc this constraint can be met for a 50MHz input signal.   There's also a trick where art the end of the couter gate period, one clocks the input under software control, and by counting the number of pulses till the counter next increments, you can calculate the count that was in the prescaler, allowing you to use Timer 0 as a 24 bit hardware timer.

No doubt others will chip in with the max. counter clock of their favourite MCU.
 
Although some MCUs may have all the logic and counters you need for high precision timing internally (e.g. some 8 bit PICs have a gated Timer 1 that can operate at up to 33.3MHz from an external high precision clock source), you may well be better off  implementing the timer gate logic externally, which can be as simple as a few gates and flipflops.   e.g. adding a single 74LVC1G74 flipflop in front of a PIC18 T0CKI pin gives you a 100MHz gated counter with an uncertainty of 1 count (due to the flipflop.)  If you are being really cheap and minimalist, use the flipflop /R input as the gate, (runs when high)  and connect both /R and /S back to PIC I/O pins, so you can pulse the Q output under program control to clock out the count in the Timer 0 prescaler by pulsing /S low while /R is low.  However adding one AND gate ahead of the flipflop clock pin to handle the gate lets you read the flipflop output before clearing it, for an extra bit of resolution.  For external gating with separate start and stop inputs, use another one as a simple SR flipflop, with 1K||33pf between its Q output and the first one + PIC I/O pin so the PIC can override it and hold the gate inactive while it cocks out the prescaler count.   That's three tinylogic gates, the cheapest USB PIC18 + commodity crystal, and a good 100MHz TCXO + a significant amount of software development to get a USB interfaced timer with 20ns resolution and on a $30 budget you can probably get 5ppm accuracy.

Similar approaches can be used with Arduino, but due to the AVR timer clock frequency limitation, you'd probably want to use an external prescaler of at least four bits.
 

Offline HendriXMLTopic starter

  • Super Contributor
  • ***
  • Posts: 1085
  • Country: nl
    • KiCad-BOM-reporter
Re: Measuring time span very precise
« Reply #18 on: September 07, 2019, 05:01:43 pm »
If your MCU has two timers with separate input capture pins, events A and B can be captured by separate timers.
In such case they may be spaced even 1 clock cycle apart, which is 1/16µs at 16MHz.
The software will then read timestamps captured by each counter and calculate the difference.

edit
Basically, we are trying to convince you that all the digital logic hardware you described in the original post is already in your MCU, just use it :)
From what I've read and understood the Mega2560 can indeed be used. It has 2 16 bit timers with capture mode. I think only one would be needed. The time between events is not that small. The 16 bit timers have a overflow bit. That overflow bit will be important in 2 interrupts,  the capture interrupt and the overflow interrupt. If the overflow interrupt hasn't counted the overflow yet, the capture interrupt might need to do that to determine what its 16+ bits are if its "near" overflowing. This checking should be done with interrupts disabled (delaying the overflow interrupt). I'm not entirely sure yet if the Arduino software makes this possible.
Using capture mode register gets the current counter and an interrupt will follow to process that value. In meanwhile no other capture events should happen: that seems doable. So thanks for sharing this option!
Will continue to digest the other ones!
« Last Edit: September 07, 2019, 05:22:06 pm by HendriXML »
“I ‘d like to reincarnate as a dung beetle, ‘cause there’s nothing wrong with a shitty life, real misery comes from high expectations”
 

Offline HendriXMLTopic starter

  • Super Contributor
  • ***
  • Posts: 1085
  • Country: nl
    • KiCad-BOM-reporter
Re: Measuring time span very precise
« Reply #19 on: September 07, 2019, 05:35:04 pm »
define precise?

I recently did a project with a 32b counter ic, driven by an over stabilised oscillator at 40Mhz, and a micro just uploads the counts when it's triggers, and takes one for the other (as mentioned previously) to get the counts difference.  The oscillator was calibrated using a GPSDO, so i've got 25ns resolution.   At that level you have to be really carefully of your triggering jitter and latency, matching your triggers so as to not create an offset to the "true" events!

even for a flight time measured in ms, your resolution looks good  (10ms = 40,000 counts!)
The nice thing about the 74LV8154 is that the current counter can be copied to an internal register, so bits can't change during readings. Does the counter IC you've used offer something similar?
“I ‘d like to reincarnate as a dung beetle, ‘cause there’s nothing wrong with a shitty life, real misery comes from high expectations”
 

Offline HendriXMLTopic starter

  • Super Contributor
  • ***
  • Posts: 1085
  • Country: nl
    • KiCad-BOM-reporter
Re: Measuring time span very precise
« Reply #20 on: September 07, 2019, 05:37:51 pm »
Simple, accurate, and cheap. Borrow an FPGA dev board
FPGA will eventually be used in the projects, but for now a bit too soon.  :-+
“I ‘d like to reincarnate as a dung beetle, ‘cause there’s nothing wrong with a shitty life, real misery comes from high expectations”
 

Offline HendriXMLTopic starter

  • Super Contributor
  • ***
  • Posts: 1085
  • Country: nl
    • KiCad-BOM-reporter
Re: Measuring time span very precise
« Reply #21 on: September 07, 2019, 05:52:46 pm »
The interrupt priorities do not fully help to solve the possible race condition, as it applies to the interrupt waiting in the queue. There still is a possibility that the capture interrupt is executes before an overflow interrupt.

The way to check for the race condition is to check the interrupt flag for the overflow inside the ICP ISR.  The value of the captured time stamp tells if a possible pending overflow interrupt should have come before ( small capture value) or after the capture event ( large capture value).

A suitable program can be found here (text in German):
https://rn-wissen.de/wiki/index.php/Timer/Counter_(Avr)#Input_Capture
Hmm you already said somewhat the same thing I later brought up. Another safe way to check for overflows would use the 2 counter compare events A and B.  On at 25% of counter one on 75% and have them count high bits as well. Using the read time stamp one of them is the most safe to use (with some extra logic). Staying many ticks away from the uncertain value.
I'm not sure whether the compare A B mode works together with the capture mode.
« Last Edit: September 07, 2019, 05:55:24 pm by HendriXML »
“I ‘d like to reincarnate as a dung beetle, ‘cause there’s nothing wrong with a shitty life, real misery comes from high expectations”
 

Offline HendriXMLTopic starter

  • Super Contributor
  • ***
  • Posts: 1085
  • Country: nl
    • KiCad-BOM-reporter
Re: Measuring time span very precise
« Reply #22 on: September 07, 2019, 06:15:06 pm »
There's not much fun and learning in using a single chip time of flight event timer breakout  board + 'canned' Arduino libraries.  If we want to do it the smart hard way (but not the hard hard way, which would be a board full of individual counter chips, or the lazy way which would be throw a FPGA at the problem), you have to understand the constraints on a practical solution.

Lets put some numbers on the problem.  A M61 Vulcan rotary cannon, has a published muzzle velocity of 1050 m/s.   Assuming a 10MHz counter clock, you'll get fractionally under 10 counts for every mm the round travels.  Nerf guns in the Rival series allegedly top out at around 30 m/s (other series are around half that), so with the same 10MHz counter clock, you'll get 333 counts per mm of round travel.   For comparison, a good fastball bowler is about as fast as the Nerf Rival dart.

At 10MHz input clock, a 16 bit counter rolls over in slightly over 6.55 ms, 24 bit in slightly under 1.68 seconds, and 32 bit in slightly over 7 minutes 10 seconds.

That means that with 100mm between sensors slower Nerf darts will probably  overflow a 16 bit timer clocked at 10MHz overflow a 16 bit counter clocked at 10MHz.  Put the sensors further apart or use the Arduino 16MHz resonator and you'll definitely overflow the AVR 16 bit timer 1 if you don't use the prescaler to drop the timer clock to 1MHz. 

Some MCUs are much better than others for high clock speed counting.  e.g. the AVRs used in 8 bit Arduino boards synchronise the external counter clock to the core clock, so with a 16Mhz resonator, the maximum input frequency is fractionally under 8MHz with an exact 50% duty cycle. 

PIC18 series chips generally do much better as they have an asynchronous up to 8 bit prescaler for timer 0 followed by a synchronous 16 bit timer, and the prescaler can be clocked at up to 50MHz, (50% duty cycle again) as long as you meet the constraint FT0CKI<N/(4/Fosc + 40ns), where N is the prescaler ratio.   
At even 1MHz Fosc this constraint can be met for a 50MHz input signal.   There's also a trick where art the end of the couter gate period, one clocks the input under software control, and by counting the number of pulses till the counter next increments, you can calculate the count that was in the prescaler, allowing you to use Timer 0 as a 24 bit hardware timer.

No doubt others will chip in with the max. counter clock of their favourite MCU.
 
Although some MCUs may have all the logic and counters you need for high precision timing internally (e.g. some 8 bit PICs have a gated Timer 1 that can operate at up to 33.3MHz from an external high precision clock source), you may well be better off  implementing the timer gate logic externally, which can be as simple as a few gates and flipflops.   e.g. adding a single 74LVC1G74 flipflop in front of a PIC18 T0CKI pin gives you a 100MHz gated counter with an uncertainty of 1 count (due to the flipflop.)  If you are being really cheap and minimalist, use the flipflop /R input as the gate, (runs when high)  and connect both /R and /S back to PIC I/O pins, so you can pulse the Q output under program control to clock out the count in the Timer 0 prescaler by pulsing /S low while /R is low.  However adding one AND gate ahead of the flipflop clock pin to handle the gate lets you read the flipflop output before clearing it, for an extra bit of resolution.  For external gating with separate start and stop inputs, use another one as a simple SR flipflop, with 1K||33pf between its Q output and the first one + PIC I/O pin so the PIC can override it and hold the gate inactive while it cocks out the prescaler count.   That's three tinylogic gates, the cheapest USB PIC18 + commodity crystal, and a good 100MHz TCXO + a significant amount of software development to get a USB interfaced timer with 20ns resolution and on a $30 budget you can probably get 5ppm accuracy.

Similar approaches can be used with Arduino, but due to the AVR timer clock frequency limitation, you'd probably want to use an external prescaler of at least four bits.

You gave a lot of stuff to think about, especially on how to go faster using MCU's. Scaling seems not to be necessary when counting overflows is handled in a correct way. I shall order some flipflops to experiment with, however solutions where the counting is uninterrupted might be beneficial in other usages. Like maybe measuring RPM's.
“I ‘d like to reincarnate as a dung beetle, ‘cause there’s nothing wrong with a shitty life, real misery comes from high expectations”
 

Offline HendriXMLTopic starter

  • Super Contributor
  • ***
  • Posts: 1085
  • Country: nl
    • KiCad-BOM-reporter
Re: Measuring time span very precise
« Reply #23 on: September 07, 2019, 06:23:30 pm »
TDC7200, easy to use, libs for arduino..

PS: with that chip (works fine) you may upgrade from the nerf darts gun to a railgun later on.. :D
I have to investigate this further, but it seem pretty advanced IC. With the option to time many things in parallel using more of them. With for an external timer very little pin burden on the Mega2560. Nice!
“I ‘d like to reincarnate as a dung beetle, ‘cause there’s nothing wrong with a shitty life, real misery comes from high expectations”
 

Offline HendriXMLTopic starter

  • Super Contributor
  • ***
  • Posts: 1085
  • Country: nl
    • KiCad-BOM-reporter
Re: Measuring time span very precise
« Reply #24 on: September 07, 2019, 07:42:11 pm »
Very interesting to think about interrupts and their order of execution again. That's how I started programming in DOS years ago. In the more modern OS's these problems got shifted to multi threading.

There critical sections, mutex's are used to be sure that access to data is synchronized: no simultaneous writing of data (or reading of dynamic data). In the DOS days one had to CLI (clear interrupts) to stop another "thread" from interrupting. Arduino has the same functionality. (On the 386 there were interrupts that could not be stopped, I recall). B.t.w. on PC's even the writing of a multiple byte (word, dword etc.) value can be interrupted, maybe for Arduino's as well.

What makes me uncomfortable with the overflow interrupt is that there's also stuff going on beyond  code (which can be protected). Like overflowing (going to zero) and the setting of the overflow flag should be atomic from the perspective of the code. Between one and the other instruction both should be updated, not only one. This I guess is the case.
However reading them will not be atomic.
It would have make me then more comfortable if there where higher order functions that would give both of them, and do a clear of the flag atomically. The caller that gets the overflow flag is the one that increments the higher bits. (Those higher bits would be read from / written to in a protected way.)

I don't think such a function can be written without interpretation of the counter, because of the external nature of updating the counter and flag.

So the next best thing would be to first read the counter, and only read the flag if the counter is less the 50% of max. (If it's more than that the flag is always 0. In reality it could be 1, but that wouldn't match the counter) If the flag is set then clear it and update the high bit counter. The same should be done in the overflow interrupt. The reason for this is only to not have the overflow happen twice without the execution of this code in between. (Anything happening more frequent than that would be usable - it should however be called before the counter reaches 50%)
99.99% of the time the overflow interrupt will be updating the higher bits. But that interrupt can't be the only one.
« Last Edit: September 08, 2019, 01:12:23 am by HendriXML »
“I ‘d like to reincarnate as a dung beetle, ‘cause there’s nothing wrong with a shitty life, real misery comes from high expectations”
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf