Skip to main content

CTUD — Count Up / Down

Structured Text up/down counter function block. Uses FBD_COUNTER; combines the roles of ladder CTU and CTD.

Operands

NameType
counterFBD_COUNTER

FBD_COUNTER Tag Members

MemberTypeMeaning
.EnableInBOOLForced to 1 each scan by the instruction call — setting it 0 has no effect
.CUEnableBOOLRising edge (0 to 1) increments ACC by 1
.CDEnableBOOLRising edge (0 to 1) decrements ACC by 1
.PREDINTPreset target count
.ResetBOOL1 clears CU, CD, DN, OV, UN and sets ACC to 0
.EnableOutBOOL1 while the instruction is executing normally
.ACCDINTAccumulated count
.CUBOOL1 while CUEnable is 1 and Reset is 0
.CDBOOL1 while CDEnable is 1 and Reset is 0
.DNBOOL1 when ACC is greater than or equal to PRE
.OVBOOL1 when ACC overflows past 2147483647 and wraps to -2147483648
.UNBOOL1 when ACC underflows past -2147483648 and wraps to 2147483647

How It Works

CTUD is the Structured Text function-block counter. It combines the roles of ladder CTU and CTD on a single FBD_COUNTER tag.

  • Each rising edge on .CUEnable increments .ACC by one.
  • Each rising edge on .CDEnable decrements .ACC by one.
  • .DN is 1 when .ACC is greater than or equal to .PRE.
  • .Reset clears .ACC and status bits.
  • An enable that is already 1 when the program starts does not count. The counter only counts a 0 → 1 change it sees while the program is running. (Prescan sets this up before the first scan.)

Example

CarsInLot.CUEnable := EntrySensor;
CarsInLot.CDEnable := ExitSensor;
CarsInLot.PRE := 20;
CTUD(CarsInLot);

LotFull := CarsInLot.DN;
Practice

Try CTUD in the Count Up Down exercise — track a running balance with separate Up and Down inputs.

Common Mistakes

  • Trying to stop the counter with .EnableIn := 0. The instruction call forces .EnableIn back to 1 every scan, so the assignment has no effect. To stop counting, hold .CUEnable and .CDEnable at 0 (no rising edges).
  • Assigning .ACC from logic to reset it (MyCounter.ACC := 0). Structured Text recomputes .ACC every scan, so a runtime write is ignored (the initial .ACC default is still honored). Clear it with .Reset := 1. The same write does take effect on the ladder CTU / CTD — so don't rely on it either way; it isn't portable.
  • CTU, CTD — the ladder-logic counterparts