# Counter (`counter`)

> Counts rising clock edges and wraps around at a set number.

![counter](https://voltecx-web.nguyenvanqui291.workers.dev/docs/reference/img/counter.svg)

[Component reference](https://voltecx-web.nguyenvanqui291.workers.dev/docs/reference/) · [繁體中文](https://voltecx-web.nguyenvanqui291.workers.dev/zh/docs/reference/control/counter/)

**Group:** Control · **Kind:** `{"block":"counter","kind":"control"}`

## When to use it

Use it to count PWM periods, divide a clock by N, or make a slow time base from a fast clock. Use D Flip-Flop to divide by two.

## Pins

| Pin | Domain | Meaning |
|---|---|---|
| `clk` | signal | Clock input; counts each rising edge |
| `rst` | signal | Reset input; holds the count at init |
| `down` | signal | Direction input; above 0.5 counts down |
| `count` | signal | The count, a whole number |

## Common parameters

- `mod`: Count where it wraps back to zero (Default: 256)
- `init`: Count at the start and after reset (Default: 0)

## Parameters

| Key | Unit | Default | Typical range | Description |
|---|---|---|---|---|
| `mod` | — | 256 |  | Count where it wraps back to zero |
| `init` | — | 0 |  | Count at the start and after reset |

_Parameter descriptions are in English in both languages._

## Model

On each rising edge of clk the count goes up by one, or down by one when down is above 0.5, and wraps from mod - 1 to 0 (or from 0 to mod - 1). While rst is above 0.5 the count is held at init, and it wins over clk. mod is a whole number from 1 up to 2^32 and init a whole number below it. The block has no direct feedthrough. A clk that is already high at t = 0 does not count.

## Common mistakes

- The output is the count itself, not a logic level, so a gate reads every count above 0 as true. Compare it first, or use a mod of 2 for a 0 and 1 output; an init that is not below mod is refused.
- rst works on a level, so a reset that stays high keeps the count at init and ignores clk edges. Use a short pulse, and drive clk from a PWM Generator output or another source the solver lands on, because edges between two solver steps are missed.

Problems rules: `compile.error`

## Datasheet and sources

There is no datasheet. mod comes from the timer or divider you are modelling, either its overflow value plus one or its division ratio N. init is the value the register is reset to.

## Example

Open the example with the command `file.openExample` and the name `demo:counter`.

---
Generated by `cargo xtask reference` from the usage texts and parameter specs. Do not edit by hand.
