> For the complete documentation index, see [llms.txt](https://help.qtech.co.nz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.qtech.co.nz/datran/datran-vi-scada/datran-dlp-ide/dlp-self-help-course/module-05-pulse-counting.md).

# Module 05: Pulse counting

Count pulses by edge detection or with the RTU's pulse counters, and reset totals at midnight with the clock registers.

A common task that will be encountered by an intrepid DLP programmer will be that of accumulating pulses that are presented to a digital input on an RTU. Usually these pulses represent a given volume of water flowing through a flow meter, but they can also be used to indicate energy consumption, rainfall, wind speed and various other quantities. The same techniques used to count physical pulses can also be used to count other slower events such as the number of times per day a given pump starts up.

This module discusses the techniques used to accumulate pulses on an RTU and shows examples of the two main types and when and where they should be used.

This module contains help on:

* conventional edge-detect pulse counting
* Pulse Analog (or `PANL`) and `PDIG` registers
* daily resets of pulse counters: `CKSEC`, `CKMIN`, `CKHOUR`, `CKDOW`, `CKDATE`, `CKMTH` and `CKYEAR`

Before you start, complete [Module 04](https://help.qtech.co.nz/datran/datran-vi-scada/datran-dlp-ide/dlp-self-help-course/module-04-analogue-setpoints.md).

## Step 1: Count pulses by edge detection

'Edge Detect Pulse Counting', or 'Conventional Pulse Counting', is a simple technique in which all of the work to count pulses is done in the DLP.

The theory is that at the end of each DLP cycle we use a spare digital register to “remember” what the current state of the digital input we are monitoring is. The next time the DLP executes it will compare this spare digital “memory” with the current state of the actual input. If the two values are different, that means there has been a change of state in the physical input, this may be a rising edge or a falling edge. Counting both will mean we end up with double the number of pulses that we should have, so we need to be careful only to count either the rising edge or the falling edge.

In older model RTUs, where the DLP cycle time was once every 100 ms, this worked quite well as it meant pulses could be counted as long as the pulse duration was at least 100 ms. In later model RTUs where the amount of functionality has vastly increased, the DLP cycle time has been slowed down to once every 500 ms (the default) to make room. However, if any pulses are shorter than the DLP execution time this approach will not be reliable. Pulses could occur in the time between DLP cycles, and as a result would not be sampled. This means that the conventional method of pulse counting is no longer as widely used as it once was, but it is still useful for counting events such as pumps running that have slow cycle times.

### Try it: example 1

This DLP counts pulses on `RDIN1`. It compares `RDIN1` with `SPD1` and if it finds that `RDIN1` is in the high state while `SPD1` is in the low state, the pulse count is incremented. Immediately after this check is made, the DLP makes `SPD1` equal `RDIN1`.

```
;*********************************
;*  DLP Self Training
;*  Module 5 Example 1
;*********************************

proginit

;   Real Digital Inputs
    equ   rdin1    rdi_Flow_Pulse

;   Notional Analog Inputs
    equ   nain1    nai_flow_total

;   Spare Digitals
    equ   spd1     spd_Flow_Pulse


    cosmask  0    2,3,4,5,6,7,8         ; Tell the RTU we don't want RDI 1 causing a COS message

progstart

begin
    tce      rdi_Flow_Pulse                         ; If the flow pulse input has gone high
    tcd      spd_Flow_Pulse                         ; But the spare digital has not gone high yet
    incanl   nai_flow_total                         ; There must have been a rising edge on RDI 1,
                                                    ; so increment the flow pulse

begin
    tce      rdi_Flow_Pulse                         ; Copy the value of the real digital input and
    ec       spd_Flow_Pulse                         ; store it in the spare register for next time around.

progend
```

If we wanted to count pulses on a negative edge instead, we would check for `RDIN1` to be in the low state while `SPD1` was high.

## Step 2: Count pulses with the pulse counters

To overcome the difficulties in counting pulses in RTUs where the DLP only runs twice per second, the Q03 firmware has been enhanced so that the DLP can ask the firmware to do the hard work for it. When this feature is used, the firmware will maintain a pulse count for each of the digital inputs on an RTU so that the DLP can read the total at any time. The firmware will automatically set the total count back to zero after each time the register is read. Effectively this register will therefore contain the number of pulses that have occurred since the last time the register was read. The RTU hardware pulse accumulators can be accessed via the DLP, enabling reliable sampling of signals up to 40Hz.

These registers are called Pulse Analog (or `PANL`) registers. By default the firmware will not be counting pulses and using a `PANL` register for each digital input, so there is a separate digital register associated with each input called the Pulse Digital (or `PDIG`) register. To enable `PANL` counting on a particular digital input, the programmer must set the associated `PDIG` register to True during the `PROGINIT` section of the DLP.

### Try it: example 2

```
;*********************************
;*  DLP Self Training
;*  Module 5 Example 2
;*********************************

proginit

;   Real Digital Inputs
    equ   rdin1    rdi_Flow_Pulse       ; The physical flow pulse input

;   Notional Analog Inputs
    equ   nain1    nai_flow_total       ; The flow total transmitted back to the base station

;   Pulse Analogs
    equ   panl1    pan_Flow_Count_Raw   ; The pulse analog register for the flow pulse wired into RDIN 1

;   Spare Analogs
    equ   spa1     spa_flow_temp        ; A temporary register to use when reading the Pulse Analog.


    initdig     pdig1    true           ; Turn on pulse counting on RDIN 1


    cosmask  0    2,3,4,5,6,7,8         ; Tell the RTU we don't want RDIN 1 causing a COS message

progstart

begin
    cpanl    pan_Flow_Count_Raw   spa_flow_temp  1        ; Copy the Pulse Analog value to the temporary spare register.
                                                          ; (This has the effect of resetting the PANL back to zero)
    addr     nai_flow_total       spa_flow_temp           ; Add the value we just got from the PANL to the running total
    cpanl    anlacc1              nai_flow_total 1        ; Copy the result into the register that holds the running
                                                          ; total.


progend
```

Each cycle, the DLP:

1. copies any new pulses to the temp register
2. adds these to the accumulator, with the result placed in `ANLACC1` (see [Module 06](https://help.qtech.co.nz/datran/datran-vi-scada/datran-dlp-ide/dlp-self-help-course/module-06-arithmetic.md))
3. copies the result back to the total

This technique can be used for RDIN 1-8 on an eXcel RTU and RDIN 1-24 on a QRTU only. It can be utilized for inputs of an expansion module if the correct firmware is used. The firmware must be the following and above: Q03 Rev 5.10, Q25 Rev 4.10 and Q26 Rev 1.10.

{% hint style="info" %}
**On the XL4 Plus**, it is an option in Workbench to configure digital input 8 for fast pulse counting (up to 40kHz). See [Digital input modes](https://help.qtech.co.nz/datran/datran-telemetry/datran-xl4-plus-rtu/configure.md#digital-input-modes).
{% endhint %}

## Step 3: Reset a total at midnight

Once you have created your pulse counters and have them working properly you will find that you will need to reset them periodically, if not the total count will most likely exceed the maximum number the DLP can deal with (65535) in a matter of days.

Most often the reset of pulse counters occurs at midnight each day, or at midnight of a certain day every week, or at midnight on the first day of a month. These different reset times will give daily, weekly, or monthly totals at the base station.

Historically the way this was accomplished was to transmit a signal from the base station on an `NDOUT` and have the DLP respond accordingly. However, this causes a traffic jam on the comms channel as all sites that need to do a reset tend to want to do them simultaneously.

Recent techniques use resets that are triggered internally in the DLP using the RTU real time clock registers. This way several sites can all carry out a midnight reset simultaneously without cluttering up the radio comms.

There are several real time clock registers that may be referenced inside a DLP. These are:

| Register | Holds                                                                 |
| -------- | --------------------------------------------------------------------- |
| `CKSEC`  | The current value of the seconds register (0-59)                      |
| `CKMIN`  | The current value of the minutes register (0-59)                      |
| `CKHOUR` | The current value of the hour register (0-23)                         |
| `CKDOW`  | The current day of the week (1-7 = Sunday to Saturday)                |
| `CKDATE` | The current date (e.g. if it was the 5th of December, `CKDATE` = 5)   |
| `CKMTH`  | The current value of the month of the year register (1-12)            |
| `CKYEAR` | The last two digits of the current year (e.g. in 2012, `CKYEAR` = 12) |

By testing one or more of these registers to see if they equal a certain value, or by waiting for one or more to change state, we can cause an event (like a pulse count reset) to occur at any time we choose.

{% hint style="warning" %}
**On the XL4 Plus,** for firmware version 7.07 and earlier the time is in UTC. This is 12 hours behind NZST. Firmware version 7.08 and later all use local time. See [Port an XL4 site to the XL4 Plus](https://help.qtech.co.nz/datran/datran-telemetry/datran-xl4-plus-rtu/upgrade-xl4-to-xl4-plus/port-xl4-site.md#dlp-changes).
{% endhint %}

### Try it: example 3

Example 3 builds on the code from example 2 and adds a midnight reset function.

```
;*********************************
;*  DLP Self Training
;*  Module 5 Example 3
;*********************************

proginit

;   Real Digital Inputs
    equ   rdin1    rdi_Flow_Pulse       ; The physical flow pulse input

;   Notional Analog Inputs
    equ   nain1    nai_flow_total       ; The flow total transmitted back to the base station
    equ   nain2    nai_yesterday_flow_total

;   Pulse Analogs
    equ   panl1    pan_Flow_Count_Raw   ; The pulse analog register for the flow pulse wired into RDIN 1

;   Spare Analogs
    equ   spa1     spa_flow_temp        ; A temporary register to use when reading the Pulse Analog.
    equ   spa2     spa_ckdow_last       ; A temporary register to detect a change in CKDOW between executions.


    initdig     pdig1    true           ; Turn on pulse counting on RDIN 1


    cosmask  0    2,3,4,5,6,7,8         ; Tell the RTU we don't want RDIN 1 causing a COS message

progstart

; Pulse Counting Code

begin
    cpanl    pan_Flow_Count_Raw   spa_flow_temp  1        ; Copy the Pulse Analog value to the temporary spare register.
                                                          ; (This has the effect of resetting the PANL back to zero)
    addr     nai_flow_total       spa_flow_temp           ; Add the value we just got from the PANL to the running total
    cpanl    anlacc1              nai_flow_total 1        ; Copy the result into the register that holds the running
                                                          ; total.
; Midnight Reset Code

begin
    ner      ckdow    spa_ckdow_last                         ; If the day of the week is not the same as last time
    jumpf    no_reset                                        ; then it must be midnight. JumpF jumps the next section
                                                             ; of code if it is NOT midnight
    cpanl    nai_flow_total    nai_yesterday_flow_total   1  ; Copy todays total to yesterdays register
    initanl  nai_flow_total    0                             ; and then reset todays total back to zero.
                                                             ; Initanl ALWAYS executes regardless of the state of the
                                                             ; accumulator. That's why we had to jump around this section
no_reset                                                     ; if ckdow had not changed.

begin
    cpanl    ckdow    spa_ckdow_last    1                 ; Copy the CKDOW register to remember what it was next time

progend
```

Things to notice:

* The section of code contains commands that will always execute such as `INITANL` or `INITDIG`. Jumps are covered in [Module 07](https://help.qtech.co.nz/datran/datran-vi-scada/datran-dlp-ide/dlp-self-help-course/module-07-logic-and-jumps.md).
* Note that because the midnight reset happens without any need to communicate with the base station, it is possible to miss the last few pulses of each day if only the "Total Today" is being reported. To get around this it is quite common to also include a "Total Yesterday" value, as shown.

## Key points

* A simple approach relies on detecting digital pulse edges and comparing them to the state of the previous value. This approach is acceptable if the duration of each pulse will always be greater than the DLP execution cycle rate.
* To enable `PANL` counting on a particular digital input, the programmer must set the associated `PDIG` register to True during the `PROGINIT` section of the DLP.
* Recent techniques use resets that are triggered internally in the DLP using the RTU real time clock registers.

**Next:** [Module 06: Arithmetic functions](https://help.qtech.co.nz/datran/datran-vi-scada/datran-dlp-ide/dlp-self-help-course/module-06-arithmetic.md)
