Amateur radio circuits on meters. A simple revolution counter - Designs of simple complexity - Circuits for beginners How to assemble an electricity meter on a microcontroller

From standard functional units of digital technology, it is not difficult to assemble an electronic stopwatch counter, similar to those produced for school physics classrooms. These devices use the pulse-counting method of time measurement, which consists in measuring the number of pulses whose repetition period is known. Such devices contain the following main components: a counting pulse generator, a control circuit (in the simplest case, its role is played by the “Start” button), a binary decimal counter, decoders and indicators. The last three nodes form a conversion decade, modeling one decimal place. It should be noted that measuring time using the pulse-counting method is accompanied by an inevitable error equal to a counting unit. This is due to the fact that the device will record the same number of pulses and, therefore, show the same time if the counting is stopped immediately after the arrival of the last pulse or just before the arrival of the previous pulse. In this case, the error will take the greatest value, equal to the time between two adjacent

Rice. 172. Recalculation decade

impulses. If you reduce the pulse repetition period and introduce additional counter digits, you can increase the measurement accuracy by the required number.

One decade of a stopwatch counter is shown in Figure 172. It consists of a binary-decimal counter on a decoder and an indicator on a neon lamp. To power the indicator, high voltage is required, therefore, according to safety regulations, the device must be used by a supervisor. The circuit uses a decoder specifically designed to work with a high-voltage indicator. Instead of a lamp, you can use lamps of other types: designed for a supply voltage of 200 V and an indication current. The microcircuit consists of a trigger with a counting input (input and a trigger divider by 5 (input). When connecting the output of a counting trigger (output 1) with the input of the divider, a binary-decimal counter. It responds to the falling edge of a positive pulse or to a negative voltage step applied to the input. In the legend, the counting edge is sometimes shown as an arrow directed towards the IC if it responds to a positive voltage step, or an arrow directed away from the IC. it reacts to a negative voltage drop.

To control the operation of the counting decade, three buttons and a switch are used. Before the counting of the decade begins

is set to zero using the “Set” button. O”, in this case a logical 1 is supplied to the counter inputs. Then the switch selects the source of the counting pulses - it can be either a trigger or a multivibrator. In the “counting mechanical closures” mode, when the button is pressed and released sequentially, binary-decimal counting occurs and the indicator lights up sequentially, numbers 1, 2, 3, etc. until number 9, then number 0 lights up and the counting is repeated. In the pulse counting mode, the input of the counter receives pulses from a multivibrator assembled according to the already known circuit in Fig. 168). To measure time in seconds, the pulse frequency must be 1 Hz. It is set by a variable resistor and a capacitance equal to

To obtain a multi-bit binary-decimal counter, they are switched on sequentially, i.e. the output of the first is connected to the input of the second, the output of the second is connected to the input of the third, etc. To set the multi-bit counter to the zero state, the inputs are combined and connected to the “Set” button. 0".

If, for example, the device is intended to be used in physics lessons, then time must be measured in a fairly wide range - from 0.001 to 100 s. To do this, the generator must have a frequency and the counter must consist of five decimal places. In this case, the digital indicator readings will look like this: 00.000; 00.001; 00.002, etc. up to 99.999 s.

The scope of application of a training counter-stopwatch can be significantly expanded if two additional devices are introduced into it - a non-contact control unit and a time delay unit. The first block must provide automatic and inertia-free switching on and off of the device. To do this, you can use the already known photo relay circuit (Fig. 76), selecting the desired sensitivity and matching the voltage of the power supplies. The control circuit must have two photosensors - one is used to turn on and the other to turn off the stopwatch counter at the moments when the rays intersect with a moving body. Knowing the distance between the photo sensors and the stopwatch readings, it is easy to calculate the speed of the body. The add-on unit uses two photocurrent amplifiers. Their output signals control the operation of a counting trigger, one of the outputs of which is connected to the stopwatch input through a transistor switch.

Other examples of the use of electronic meters can also be given. For example, a machine that simulates a game of dice consists of the already discussed decade of

And a neon lamp controlled by multivibrator pulses (see Fig. 168, 172). Players take turns pressing the button that interrupts the count. The one whose indicator shows the highest number wins. The moment the counter stops, as well as the moment the cube with points from 1 to 6 stops, is determined by random reasons, therefore the counting decade together with the multivibrator is an electronic random number sensor. Let's give more examples of its use in various gaming situations.

When checking the reaction speed of players, a resistor sets a certain frequency of operation of the multivibrator and the speed at which the indicator numbers change (see Fig. 168 and 172). Participants in the game are asked to press the multivibrator button each time the indicator shows a certain, pre-selected number. The higher the switching frequency, the more difficult it is to fulfill this condition. The slowest ones are eliminated first; the winner is the player with the best reaction. In another, more difficult version of the game, you need to continue pressing the button at a pace set by the judge after the indicator disappears. To do this, close it with a mechanical curtain or turn it off with a button

A counting decade together with a multivibrator is especially convenient to use in games if its power supply is made autonomous, that is, not connected to the network. In this case, a seven-segment LED indicator controlled by an integrated circuit decoder is used. We are already familiar with this microcircuit and indicator (Fig. 150, 163). The multivibrator and counter circuits remain unchanged. The circuit of a random number sensor operating from a 5 V source is shown in Figure 173.

An example of a more complex device that operates on the basis of an electric meter is a time delay unit, or timer. Figure 174 shows a schematic diagram of a timer that allows you to turn on various loads for a time from 0 to 999 s. It consists of a three-digit decimal counter assembled on a microcircuit of three decoders on a multivibrator chip and a control circuit on a microcircuit, as well as a microcircuit. The source of counting pulses is a multivibrator tuned to a frequency of 1 Hz. Its pulses are fed to the input of a three-digit decimal counter. Binary codes from each digit are fed to decoders. At their outputs, zero signals appear sequentially as they arrive at the inputs

Rice. 173. Recalculation decade with LED indicator

corresponding binary codes. Setting the required time delay is carried out by switches connecting the outputs of the decoder with the elements of the microcircuit. The inputs of the elements And are connected in pairs to obtain an element. The switch sets units of seconds, the switch tens of seconds and the switch hundreds of seconds. If, for example, the switches are connected to pins 2, 3 and 7 of the decoder, then there will be three 0s at the inputs of the OR-NOT element only at the moment when the counter records 237 pulses or a period of time equal to 237 seconds has passed since the start of counting. In this case, a 1 signal will appear at the output of the OR-NOT element. Until this moment, for all binary codes of the counter, the output of the logical element was a zero signal.

The timer control circuit works as follows. The “Stop” button is first pressed; as a result, the RS trigger assembled on the microcircuit is set to the zero state. From the direct output, the zero voltage level is supplied to a 1/77 transistor, the emitter circuit of which includes an electromagnetic relay winding. The transistor and relay are off. At the same time, a high level appears at inverse output 6, which serves as a reset signal for the counter. When you press the “Start” button, the RS trigger goes into the single state, and 3 appears on the direct output. high voltage level, sufficient to open the 1/77 transistor and operate the relay. Its contacts close the load power supply circuit. Simultaneously

(click to view scan)

the zero voltage level removed from the inverse output of the trigger “opens” the counter. The counter operates until output signals corresponding to the dialed number appear at the decoder outputs. In this case, as already mentioned, a single signal appears at the output, which is fed through the inverter to the input of the trigger. It is set to the zero state and, accordingly, the transistor, electromagnetic relay and load are turned off. The counter is set to zero.

The timer will show the current time in seconds if LEDs are connected to the decoder outputs. Time counting will become more convenient if the binary decimal codes of the counters are supplied to decoders working in conjunction with seven-segment indicators

If you are faced with the task of implementing a pulse counter, counting tens, hundreds or thousands, then for this it is enough to use a ready-made assembly - the CD4026 microcircuit. Fortunately, the microcircuit practically eliminates all worries about wiring the microcircuit and additional matching elements. At the same time, one CD4026 counter is capable of “counting” only up to 10, that is, if we need to count up to 100, then we use 2 microcircuits, if up to 1000, then 3, etc. Well, let's say a few words about the chip itself and its functionality.

Description of operation of the CD4026 counter

Initially, we present the appearance and functional designation of the pins on the counter chip

Despite the fact that everything is in English, in principle everything here is clear! The counter readings increase by 1 unit each time a positive pulse arrives at the “clock” contact. In this case, a voltage appears at outputs a-g, which, when applied to a 7-segment indicator, will display the number of pulses.

The “reset” contact resets the counting readings when shorted to +.

The "disable clock" pin must also be connected to ground.

The “enable display” contact, in fact, contact 3 must be connected to the positive.

Contact “÷10” is actually output 5, sends a signal about the counter overflow, so that a similar counter can be connected to it and start counting for 10, 100, 1000...

The “not 2” contact takes the value LOW if and only if the counter value is 2. Otherwise, HIGH.

The operating supply voltage of the microcircuit is 3-15 V. That is, it has a built-in stabilizer. Now let’s talk about how to connect this microcircuit to the assembly, that is, about the circuit diagram.

Connection diagram for a pulse counter on a CD4026 chip

Take a look at the diagram. It counts light pulses of changes in resistance for a photoresistor. As a photoresistor, you can use, say, a 5516 photoresistor. So, due to a change in resistance, the potential at the base of the transistor also shifts. As a result, current begins to flow through the collector-emitter circuit, which means a pulse is supplied to input 1 of the microcircuit, which must be counted.
As soon as the first microcircuit counts 1 ten, then one pulse appears at pin 5 indicating the “overflow” of the counter. Ultimately, this impulse is supplied to a second microcircuit, which operates on exactly the same principle. But in this case, the microcircuit no longer counts units, but tens. If you add 3 microcircuits, then it will be hundreds, etc.

To reset to 0, just apply a plus to the legs of 15 microcircuits. The microcircuit is designed to work with a 7 segment indicator. When applied to one of the outputs of this indicator, we get the number we need. Take a look at the table...

In conclusion, I would like to say once again that the pulse counter in this case is functional and will require minimal costs and knowledge from you. What is also important is that the circuit does not need to be configured, at least the digital part. The only thing is that you may have to “play around” with resistors and a photoresistor at the input.

Everyone knows why a microcalculator exists, but it turns out that in addition to mathematical calculations, it is capable of much more. Please note that if you press the “1” button, then “+” and then press “=”, then with each press of the “=” button the number on the display will increase by one. Why not a digital counter?

If two wires are soldered to the “=” button, they can be used as a counter input, for example, a turns counter for a winding machine. And after all, the counter can also be reversible; to do this, you must first dial a number on the display, for example, the number of turns of the coil, and then press the “-” button and the “1” button. Now, each time you press “=” the number will decrease by one.

However, a sensor is needed. The simplest option is a reed switch (Fig. 1). We connect the reed switch with wires parallel to the “=” button, the reed switch itself stands on the stationary part of the winding machine, and we fix the magnet on the movable one, so that during one revolution of the coil the magnet passes near the reed switch once, causing it to close.

That's all. You need to wind the coil, do “1+” and then with each turn, that is, with each turn the display readings will increase by one. You need to unwind the coil - enter the number of turns of the coil on the microcalculator display, and make “-1”, then with each revolution of unwinding the coil, the display readings will decrease by one.

Fig.1. Connection diagram of the reed switch to the calculator.

And, suppose you need to measure a large distance, for example, the length of a road, the size of a plot of land, the length of a route. We take a regular bicycle. That's right - we attach a non-metallic bracket with a reed switch to the fork, and we attach the magnet to one of the spokes of the bicycle wheel. Then, we measure the circumference of the wheel, and express it in meters, for example, the circumference of the wheel is 1.45 meters, so we dial “1.45+”, after which with each revolution of the wheel the display readings will increase by 1.45 meters, and as a result, the display will show the distance traveled by the bike in meters.

If you have a faulty Chinese quartz alarm clock (usually their mechanism is not very durable, but the electronic board is very reliable), you can take a board from it and, according to the circuit shown in Figure 2, make a stopwatch out of it and a calculator.

Power is supplied to the alarm clock board through a parametric stabilizer on the HL1 LED (the LED must have a direct voltage of 1.4-1.7V, for example, red AL307) and resistor R2.

The pulses are generated from the control pulses of the stepper motor of the clock mechanism (the coils must be disconnected, the board is used independently). These pulses travel through diodes VD1 and VD2 to the base of transistor VT1. The alarm board supply voltage is only 1.6V, while the pulse levels at the outputs for the stepper motor are even lower.

For the circuit to work properly, diodes with a low level of forward voltage, such as VAT85, or germanium are required.

These pulses arrive at the transistor switch at VT1 and VT2. The collector circuit VT2 includes the winding of a low-power relay K1, the contacts of which are connected in parallel to the “=” button of the microcalculator. When there is +5V power, the contacts of relay K1 will close at a frequency of 1 Hz.

To start the stopwatch, you must first perform the “1+” action, then use switch S1 to turn on the power to the pulse shaper circuit. Now, with every second, the display readings will increase by one.

To stop counting, simply turn off the power to the pulse shaper using switch S1.

In order to have a count for reduction, you must first enter the initial number of seconds on the microcalculator display, and then do the “-1” action and turn on the power to the pulse shaper with switch S1. Now, with every second, the display readings will decrease by one, and from them you can judge how much time is left until some event.

Fig.2. Scheme for turning a Chinese hanger into a stopwatch.

Fig.3. Circuit diagram of an IR beam intersection counter using a calculator.

If you use an infrared photo sensor that works at the intersection of the beam, you can adapt the microcalculator to count some objects, for example, boxes moving along a conveyor belt, or by installing the sensor in the aisle, count people entering the room.

A schematic diagram of an IR reflection sensor for working with a microcalculator is shown in Figure 3.

The IR signal generator is made on an A1 chip of type “555” (integrated timer). It is a pulse generator with a frequency of 38 kHz, at the output of which an infrared LED is switched on. The generation frequency depends on the C1-R1 circuit; when setting up by selecting resistor R1, you need to set the frequency at the output of the microcircuit (pin 3) to close to 38 kHz. The HL1 LED is placed on one side of the passage, putting an opaque tube on it, which must be precisely aimed at the photodetector.

The photodetector is made on the HF1 chip - this is a standard integrated photodetector of the TSOP4838 type for remote control systems for TVs and other home appliances. When a beam from HL1 hits this photodetector, its output is zero. In the absence of a beam - one.

Thus, there is nothing between HL1 and HF1 - the contacts of relay K1 are open, and at the moment of the passage of any object, the relay contacts are closed. If you perform the “1+” action on the microcalculator, then with each passage of an object between HL1 and HF1, the microcalculator display readings will increase by one, and from them you can judge how many boxes were shipped or how many people entered.

Kryukov M.B. RK-2016-01.

This device is designed to count the number of revolutions of the shaft of a mechanical device. In addition to simple counting with indication on the LED display in decimal numbers, the counter provides information about the number of revolutions in a binary ten-bit code, which can be used in the design of an automatic device. The counter consists of an optical speed sensor, which is an optocoupler consisting of a constantly glowing IR LED and a photodiode, between which there is a disk of opaque material in which a sector is cut out. The disk is attached to the shaft of a mechanical device, the number of revolutions of which must be counted. And, a combination of two counters - a three-digit decimal counter with output to seven-segment LED indicators, and a ten-digit binary one. The counters operate synchronously, but independently of each other. The HL1 LED emits a continuous light stream, which enters the photodiode through a slot in the measuring disk. When the disk rotates, impulses are generated, and since there is only one slot in the disk, the number of these impulses is equal to the number of revolutions of the disk. The Schmitt trigger on D1.1 and D1.2 converts voltage pulses on R2, caused by a change in the photocurrent through the photodiode, into logic level pulses suitable for perception by counters of the K176 and K561 series. The number of pulses (number of disk revolutions) is simultaneously counted by two counters - a three-decade decimal counter on chips D2-D4 and a binary one on D5. Information about the number of revolutions is displayed on a digital display, composed of three seven-segment LED indicators H1-H3, and in the form of a ten-bit binary code, which is removed from the outputs of the counter D5. Resetting all counters to zero at the moment the power is turned on occurs simultaneously, which is facilitated by the presence of element D1.3. If you need a zero button, it can be connected in parallel with capacitor C1. If you need the reset signal to come from an external device or logic circuit, you need to replace the K561LE5 microcircuit with K561LA7, and disconnect its pin 13 from pin 12 and C1. Now zeroing can be done by applying a logical zero from an external logical node to pin 13 of D1.3. The circuit can use other seven-segment LED indicators similar to ALS324. If the indicators have a common cathode, you need to apply zero, not one, to pins 6 D2-D4. K561 microcircuits can be replaced with analogues of the K176, K1561 series or imported analogues. LED - any IR LED (from the remote control of the equipment). Photodiode - any of those used in remote control systems of TVs of the USCT type. The setting consists of setting the sensitivity of the photodiode by selecting the value of R2.

Radioconstructor No. 2 2003 p. 24

Often, when operating a microcontroller device, there is a need to count “anthropomorphic” time - how many fractions of a second the LED should glow, the maximum period of double-click time, etc. In general, count not only nano- and microseconds, but also tens of milliseconds, or even seconds , minutes and even hours (I'm afraid to say about days...).
At the same time, in microcontrollers it is often necessary to simultaneously deal with microseconds - pulse periods, anti-bounce waiting, etc.
There are also devices that operate continuously for many hours and even days - aviation equipment, automobile equipment, downhole devices (sometimes we are talking about continuous operation for several days). In these cases, timers and 8-bit variables must not overflow.
I would like to combine all this into one elegant and universal solution - to have a means of measuring time with microsecond accuracy that does not overflow for several days.
Why not? I suffered for some time and came up with a solution for 8-bit AVR microcontrollers. To do this, I used an 8-bit timer-counter and a 4-byte variable. I don’t currently work with PICs and AT89, and I’m not familiar with other embedded platforms. However, if readers help, I’ll do it for them too.
Advantages – the code is highly repeatable (I’m already making the 5th device with it); ease of operation (interrupts are not used for the client part of the work); the client part of the code is conditionally platform-independent; in the interrupt - one summation operation (but, however, for a 4-byte value); there is no external device - a real time timer.
I found only one drawback - one such useful and always needed timer is busy...
The article will be of interest primarily to beginners - I didn’t discover America here.

Theory

So, I have at my disposal a device based on Atmega16A with 12MHz quartz. Let's take its timer-counter 0. This is an eight-bit timer - that's enough for us. Why? We count:
  1. we take 12 MHz from the quartz and take the division factor by 8 - we get a frequency of 1500 KHz;
  2. We take the CTC mode (reset on coincidence) and set the interrupt to coincide with 150 - we get the interrupt frequency of 10 KHz;
  3. on this very interrupt we increment the variable (an increment is obtained every 0.1 milliseconds);
  4. if it is an unsigned 32-bit value, it will overflow after approximately
    • 429496729.6 milliseconds;
    • 42949.7 seconds;
    • 7158.3 minutes;
    • 119.3 hours;
    • 4.97 days.
In other words, this solution creates a timer with an accuracy of 0.1 milliseconds for (almost) 5 days (we must, however, take into account that real quartz has an error - more on that later). And if you also analyze the value of timer 0 itself - it is incremented every 2/3 microseconds - then you can get a counter with an accuracy of 0.67 microseconds.
Enough? Behind my eyes. Using a 0.1 millisecond counter, in my projects I:
  • I count the duration of glow and pauses between LEDs;
  • I take into account timeouts when working with UART, USB;
  • I set all sorts of situations in the test equipment - complex spatio-temporal combinations;
  • I maintain specified time intervals when polling the ADC and other sensors;
  • I tell the computer the time of my (the device’s) operation and transmit information at a given time interval;
  • Taking into account the counter down to the microsecond, I carry out anti-bounce control when pressing keys, analyzing pulses in long lines.
And all this easily fits into ONE ATmega16 CONTROLLER! Moreover, this is not Assembler, but cross-platform C! And no external real-time counter!
Not bad, right?

Setting up for AVR

How to do all this in AVR?
First of all, we create an external variable, which I call “DeciMilliSecond”:
// in main.h typedef unsigned long dword; // unsigned 32-bit integer extern volatile dword dmsec; // 0.1msec // in main.c volatile dword dmsec;
As @no-smoking correctly noted, this variable must be volatile so that the compiler does not try to optimize it.
I initialize this variable in a function:
dmsec = 0;
Next, I set the operating mode of timer 0:
// . timer 0 – 0.1msec Timer0_Mode (TIMER_Mode_CTC | TIMER0_Clk_8);
Timer0_Cntr(149);
Timer_Int(Timer0_Cmp); At the same time, in some MCU_init.h I declare everything that is needed:<< 1) // совпадение таймера 0 // . TCCRn #define WGM1 (1 << 3) #define CS1 (1 << 1) // . источник сигнала для таймера 0 #define TIMER0_Clk_8 CS1 // предделитель 8 // . режим работы таймера #define TIMER_Mode_CTC WGM1 // CTC (сброс при совпадении) // . настройка таймера #define Timer_Int(Mode) TIMSK = (Mode) #define Timer0_Mode(Mode) TCCR0 = (Mode) #define Timer0_Cntr(Cntr) OCR0 = (Cntr)
// in mcu_init.h #include
// . TIMSK #define Timer0_Cmp (1
Well, then, when possible, I enable interruptions:
#asm("SEI") It remains to describe the interruption. This is easier than everything before:
#include

interrupt Timer0_Compare (void) ( ++dmsec; )

That's it, the timer is described, configured and running!

Setting for PIC

Here's what dear PIC fans told me:
At peaks this can be easily repeated using the Timer2 module. It has a similar interrupt function by coincidence.
PR2 = 75 - the value at which the timer will reset and generate an interrupt
T2CON.T2CKPS = 2 - prescaler 1:16

T2CON.T2OUTPS = 0 - without postscaler
T2CON.TMR2ON = on - timer is enabled
IPR1.TMR2IP = 1 --high priority interrupt
PIR1.TMR2IF = off -- reset the interrupt flag

PIE1.TMR2IE = on -- enable interrupt when TMR2 and PR2 coincide
INTCON.GIE = ​​on -- enable interrupt processing

As you can see, the prescaler here is 2 times larger, so PR2 is 2 times smaller.

These settings will generate interrupts with a frequency of 10 kHz at a system frequency of 48 MHz (the timer is set to Fosc/4) - the standard frequency for USB Full Speed.
Usage
#include "main.h" // here is the dmsec variable, next_USB_timeout #include "FT245R.h" // here are functions for working with the USB module #include "..\Protocol.h" // here is the microcontroller-computer exchange protocol // * * // ** Analyze USB packets // ** void AnalyzeUSB (void) ( #define RECEIVE_BYTE(B) while (!FT245R_IsToRead)\ ( if (dmsec > end_analyze) return; )\ B = FT245_ReadByte (); #define RECEIVE_WORD(W) // similar for 2 bytes #define RECEIVE_DWORD(W) // similar for 4 bytes dword end_analyze, d; NewAnalyze: if (!FT245R_IsToRead) // no packets return; end_analyze = dmsec + max_USB_timeout; for the current analysis next_USB_timeout = dmsec + MaxSilence_PC_DEV; // timeout for general exchange RECEIVE_BYTE (b) // packet header switch (b) ( case SetFullState: RECEIVE_DWORD (d); // read the word is_initialized = 1; // process ChangeIndicator () ; break; ) // switch (pack) goto NewAnalyze; #undef RECEIVE_BYTE // cancel #define #undef RECEIVE_WORD #undef RECEIVE_DWORD )
The macro functions RECEIVE_BYTE, RECEIVE_WORD, RECEIVE_DWORD implement reading procedures taking into account the timeout for a given exchange phase. As a result, if something hangs on the other side, the microcontroller will not go into hibernation. Please note - WatchDog is not needed! And all thanks to the variable/constant max_USB_timeout, which sets the timeout with an accuracy of 0.1 milliseconds.
The analysis of “silence on air” using the next_USB_timeout variable is implemented in the same way. This allows the microcontroller 1) to know that the computer has disappeared somewhere, 2) to signal this somehow (in my case, the “error” LED lights up). The MaxSilence_PC_DEV constant/variable allows you to vary the concept of “silence” within the widest range – from a fraction of a millisecond to several days.
All other points are implemented similarly.
If you need to use a microsecond counter, then a comparison function appears there:
#define GetUSec(A,B) ( #asm ("CLI"); A = dmsec; B = TCNT0; #asm ("SEI"); ) // ** // ** Time difference between events accurate to 2/3usec // ** dword Difference (dword prev_dmsec, byte prev_usec) ( dword cur_dmsec; byte cur_usec; ​​dword dif; // . note the current time GetUSec (cur_dmsec, cur_usec); // calculate the difference dif = cur_dmsec - prev_dmsec; dif<<= 8; if (cur_usec < prev_usec) dif += 255 + (dword) cur_usec - prev_usec; else dif += cur_usec - prev_usec; return dif; }
The function is passed the previous point in time - the previous value of dmsec and timer 0.
First, we use the GetUSec macro to stop interrupts so that the value of dmsec and the counter are not corrupted at the time of copying. And copy the current time.
Next, we convert the time difference to a 2/3 microsecond format, taking into account overflow.
Well, let's return this time.
And then we use this in a regular if to control anti-bounce and other measures. Just don’t forget to also pause interrupts when marking the current moment in time - or better yet, use the GetUSec macro.

results

This timer turned out to be an extremely convenient solution for me. I think it will be useful to you too. And I used it in my following projects:
  • Switchboard fencing situations. This is a hefty half-meter board with three controllers - ATmega128 as the central one and ATmega64 as two auxiliary ones (right and left sides). There is no galvanic connection between the three controllers and their components - power supply is based on ionistors, communication through optocouplers. The central controller charges groups of some ionistors and at this time powers both sides from other ionistors. Here we had to make a multi-stage algorithm for switching all this in order to minimize the interconnection. In particular, we are talking about the coordinated work of 8 relays - timers work here for 3.3 ms (guaranteed relay response time). Well, in fact, both sides control 10 relays and about half a hundred multiplexers. All this equipment works with clearly defined time characteristics (with an accuracy of 1 ms, maximum duration is 6 seconds). Well, and, in the end, banal timeout for USB, UART.
  • Depth sensor. Here I am solving another problem (a project in progress). There are two conductors (many meters long) that define the situation “shift up by 1 cm” and “shift down by 1 cm”. There are many ways to set a direction. In any case, these are certain combinations of impulses. Using this timer, I determine bounce and the duration of a stable pulse. The maximum permissible bounce time (10 microseconds is enough here), anti-bounce wait, and minimum/maximum pulse duration are set from the computer. Well, there is a debug mode - the sensor becomes a logic analyzer. This allows you to debug the operation of the line and adjust the coefficients. Well, again timeout, LEDs.
  • Analog signal sensor. A banal 8-channel ADC. Here I use a timer to take the necessary pauses.
Dear habra users from other platforms can tell me the initialization code for the corresponding timer, as well as the rules for accessing it - I’ll add it here. It may be necessary to select different times for other platforms. But in any case, it should be something within a few units of microseconds for the timer itself and something a multiple of 100 microseconds for the counter variable. Because, as it turns out, sometimes one millisecond is not enough.
Share