PLC Programming SAPLC ProgrammingSOUTH AFRICA
Menu

exercises · South Africa

PLC Up Down Counter Example: Parking and Reconciliation

Study a PLC up down counter example with entry and exit traces, simultaneous events, count limits and reconciliation for South African automation learners.

Conceptual PLC up down counter example study illustration with conveyor boxes and laptop tally marks
Conceptual learning illustration; not a validated circuit, program screenshot or physical test result.

This PLC up down counter example uses a fictional 50-space parking display to explain entry events, exit events, simultaneous changes and count reconciliation. You will calculate a bounded occupancy estimate from two Boolean input histories, test the zero and full boundaries, then compare the model with a native CTUD interface.

The display is a disconnected learning model. Its Count is an estimate derived from accepted events, not an independently verified number of vehicles. There is no boom-control circuit, detector installation, access-control system or physical safety function in this lesson. Keeping that distinction clear makes the arithmetic and its limitations easier to assess.

Complete the bottle-counting exercise first if rising edges and reset overlap are unfamiliar. An up/down counter adds another event stream, which creates a new question: what should happen when both streams report a fresh event in the same evaluation?

Define the counting policy before choosing CTUD

The basic exercise has EntryInput, ExitInput and ResetRequest. Capacity is fixed at 50. Initialise Count to zero for a declared empty virtual exercise, and sample the two current input levels into their previous-value variables before normal evaluations.

A rising EntryInput contributes plus one. A rising ExitInput contributes minus one. If both rise in the same evaluation, their net change is zero. If neither rises, Count is unchanged. Clamp the resulting value between zero and Capacity. ResetRequest has priority over both events and sets Count to zero.

Update both input-history variables on every evaluation, including reset and boundary cases. An event discarded at a boundary is not queued for later acceptance. A level held through reset is not automatically another rising edge when reset is released.

These are explicit rules for this paper model. They are not asserted to be the undocumented simultaneous-input behaviour of every CTUD instruction. A native block needs to be checked against the intended policy before you use its output as the answer to the exercise.

Do not use a reset-to-zero command as a substitute for finding out actual occupancy. Zero is a valid initial condition for a known empty simulation. If an estimate needs correction to another value, use the reconciliation revision later in the lesson and record the evidence behind the replacement value.

Separate raw levels, events and displayed values

VariableMeaningRole
EntryInputCurrent virtual entry-detection levelBoolean input
ExitInputCurrent virtual exit-detection levelBoolean input
PreviousEntryEntry level at the preceding evaluationBoolean state
PreviousExitExit level at the preceding evaluationBoolean state
CountCurrent bounded occupancy estimateInteger state
CapacityFixed value 50Integer parameter
FullCount has reached CapacityDerived result
SpacesEstimateCapacity minus CountDerived result

A level and an event are different. An entry input that remains true for five evaluations can produce one rising edge, while alternating false and true values can produce several. Neither pattern, by itself, explains how many real vehicles passed a detector or whether they entered the monitored area.

Keep the estimate label on the spaces display. With Count equal to 12, SpacesEstimate is 38 by arithmetic. Whether 38 spaces actually exist requires other evidence. Two complementary indicators can agree perfectly with the stored count while the stored count disagrees with reality.

In a vendor development tool, declare the variables and counter instance using the correct types and names. The CODESYS learning guide and Allen-Bradley learning guide explain why software family and controller context matter. A generic address translation does not establish instruction compatibility.

Conceptual sensor, controller and conveyor illustration for distinguishing signals from program values
Conceptual learning illustration; not a validated circuit, program screenshot or physical test result.

Write the bounded model explicitly

Calculate both raw input edges before changing Count:

EntryEdge = EntryInput AND NOT PreviousEntry
ExitEdge = ExitInput AND NOT PreviousExit
Delta = integer(EntryEdge) - integer(ExitEdge)

If ResetRequest:
    Count = 0
Else:
    Count = clamp(Count + Delta, 0, Capacity)

PreviousEntry = EntryInput
PreviousExit = ExitInput
Full = Count >= Capacity
SpacesEstimate = Capacity - Count

Here integer(false) is zero and integer(true) is one. The clamp function returns the lower bound for a value below zero, the upper bound for a value above Capacity and the value itself otherwise. Calculate Delta before clamping; the order is part of the specification.

There is one Count assignment decision per evaluation. Two separate pieces of code that each modify Count and clamp it can produce a different answer at a boundary. That is not a reason to claim separate counters are always wrong; it is a reason to specify how updates combine and to test the actual implementation.

Use a signed intermediate type capable of representing the possible temporary results. In this small model Count plus Delta can range from minus one to 51 before clamping. Choosing a type that cannot represent minus one would change what the arithmetic can express before the clamp is reached.

The pseudocode is a mathematical model, not a compiled project for every PLC. If you implement it in structured text or ladder, document how Boolean-to-integer conversion, arithmetic and bounds are expressed in your environment. Compare the end-of-evaluation results against the tables below.

Work through a sequence with simultaneous events

Start with Count zero, both input levels false and both previous levels false. A 1 means true. The Count column contains the value after each evaluation.

StepEntryInputExitInputResetRequestCountExplanation
10000No events
21001Entry edge
31001Held entry level
40001Release
51101Both edges; net zero
60001Both released
70100Exit edge
80000Release
90100Extra exit clamped at zero
101101New entry; exit remains held
111110Reset takes priority
121100Held levels after reset are not new events
130000Both releases observed
141001Fresh entry edge

Step five is a net-zero update because both inputs rise from the preceding false values. Step ten is different: only EntryInput rises, while ExitInput was already true. Looking only at the current pair 1,1 cannot tell you which events occurred. You need the previous pair as well.

Steps nine and ten also show that the exit rejected at zero is not saved as a future decrement. The model still records its input level. This prevents a held exit signal from becoming a new event merely because the count later increases.

Illustrated learning desk with a notebook and laptop for planning Boolean logic test cases
Conceptual learning illustration; not a validated circuit, program screenshot or physical test result.

Test zero, full and update order

Prepare a separate fixture with Count 49 and both previous inputs false. Apply input pairs (1,0), (0,0), (1,0), (0,0), (0,1). The expected counts are 50, 50, 50, 50, 49. Full becomes true on the first entry and clears on the final exit. The additional entry at the upper bound is discarded under the chosen policy.

Now test simultaneous fresh entry and exit at Count zero. Delta is zero, so Count remains zero. Repeat at Count 50: it remains 50. These results follow from combining the events before clamping.

Compare an intentionally different implementation at zero: subtract and clamp first, then add and clamp. An exit followed by an entry within that update procedure produces one. At Capacity, adding and clamping first, then subtracting can produce 49. The difference comes from operation order, even though the two input events are the same.

This is why “up and down cancel” must be an explicit requirement rather than an assumption about arbitrary code. If your native CTUD has a documented simultaneous-input policy, record it. If that policy differs from this lesson, either adapt the surrounding logic or clearly label the implementation as a different model.

Clamping also loses information about events that exceed the bounds. If an extra entry at Count 50 is ignored, a later exit changes Count to 49 even though the ignored event may matter to a real occupancy estimate. The arithmetic remains within range, but boundedness is not proof of accuracy. Keep boundary rejections as separate diagnostic evidence if you extend the exercise.

Read the actual CTUD interface

The CODESYS CTUD reference documents rising-edge CU and CD inputs, RESET, LOAD, PV, CV, QU and QD. It explicitly notes its WORD type for PV and the difference from the INT type stated in the standard. Its LOAD input sets CV to PV. Consult the current tool declaration rather than copying a spelling from an example without checking it.

Schneider Electric's CTUD interface for the referenced Machine Expert version describes INT values, rising-edge increment and decrement, reset to zero and load from PV. Its instructions say reset and load must be false to enable ordinary counting. Those interface details do not answer every surrounding application question about initial conditions, simultaneous edges or estimate reconciliation.

A particular block can use PV both as a load value and as a threshold associated with an output. That creates a practical design question if Capacity is 50 but you want to reconcile Count to 12. Do not change a shared preset to 12 and assume the FULL threshold remains 50. Keep the application capacity separate and inspect how the chosen block supports loading or state correction.

The model in this article supplies a policy you can test. A native instruction supplies an implementation with documented behaviours and limits. Matching one to the other is part of the exercise, not something achieved merely by placing a block labelled CTUD in a diagram.

Two illustrated learners reviewing a controller example beside a guarded training conveyor
Conceptual learning illustration; not a validated circuit, program screenshot or physical test result.

Why count-dependent input gating can invent an edge

Consider CD = ExitInput AND (Count > 0). At Count zero with ExitInput held true, CD is false. If a new entry raises Count to one while ExitInput remains true, the gated expression can become true without a fresh exit transition. An edge-sensitive input observing that expression may then see a rising edge created by the count condition.

The main model avoids that ambiguity by detecting the raw ExitInput edge first and applying the lower bound to the numeric result. It updates PreviousExit even when an exit is rejected at zero. The held input therefore remains held rather than being reclassified when Count changes.

Use steps nine and ten of the main trace to investigate this. Record raw ExitInput, PreviousExit, Count and the gated expression separately. Do not predict a native block's exact result without specifying when the expression is evaluated and how its edge memory and reset inputs behave.

The bottle-counter lesson demonstrates a related problem when crate availability is included inside an edge-sensitive signal. Recognising the shared principle helps you reason about permissions and boundaries without copying a fix intended for a different input history.

Reconcile an estimate instead of blindly clearing it

For a second project revision, add an explicit reconciliation request and a supplied ObservedCount. In the fictional exercise, ObservedCount is an independently supplied integer from zero to 50. It is not automatically reliable just because a user typed it into a field.

Define this priority: ResetRequest first, reconciliation second, normal entry/exit arithmetic third. A valid reconciliation replaces Count with ObservedCount and discards that evaluation's entry/exit events. An invalid value leaves Count unchanged, reports ReconcileRejected and also discards those events. Update both input histories in every case.

For example, with Count eight and a valid supplied observation of 12, reconciliation produces Count 12 and SpacesEstimate 38. If an entry edge arrives on that same evaluation, it is not added on top. If the entry stays held on the next evaluation, the updated history prevents counting it then as a delayed event.

Test values minus one, zero, 12, 50, 51 and a non-integer such as 12.5. Only the integers inside the declared range are valid. Keep rejected requests visible in the test record rather than silently clamping an invalid reconciliation value and presenting it as an observation.

In a real counting process, reconciliation also needs a defined observation time and a way to account for movement during the check. This lesson supplies no operational procedure for that. Its purpose is to distinguish arithmetic correction from evidence about actual occupancy and to make event priority reproducible.

Illustrated learner comparing program observations with a guarded conveyor training model
Conceptual learning illustration; not a validated circuit, program screenshot or physical test result.

Filtering does not establish vehicle identity

A held input counts once under the edge model. A signal that goes false and true repeatedly can create several events. An on-delay filter can reject some short high intervals, but an arbitrary 200 ms preset does not guarantee that every genuine event survives or every repeated detection disappears.

The relevant evidence includes the observed signal duration, gaps, acquisition conditions and the meaning assigned to a detection. A Boolean input trace alone cannot establish vehicle direction, completion of passage or whether two detections describe the same object. Do not assert a particular detector responds to pedestrians or other objects without evidence about that device and installation.

Use synthetic traces to explore the software: a long held level, two separated pulses, a pulse shorter than the chosen qualifier and an interval that crosses a threshold between observations. Keep raw input, qualified input and accepted edges in separate columns. The timer exercise explains why observation timing belongs in such a record.

For an extended model, you could add explicit passage states or another input, but first define the event that changes occupancy. More sensors or more code do not remove the need for that definition. Keep any physical access-control design outside this disconnected lesson.

Make the learning evidence useful

A South African learner comparing PLC courses can ask whether counter exercises include simultaneous events, initial state, count boundaries and reconciliation. Listing CTUD on a syllabus does not show whether learners examine these cases. The online PLC training guide covers broader questions about format, access and practical support.

For a Sandton evening study group, a Durban learner or a Western Cape college class, this small example can be predicted on paper and tested later in a development environment. These are possible study contexts, not claims about training premises or current bookings. The engineering student guide explains how to present a reproducible project without overstating its scope.

Save the requirement revision, input meanings, initial values, trace tables and actual results. Include the operation-order counterexample and one rejected reconciliation request. State whether the results came from a paper model, a custom program or a native instruction with a specific version.

The maintenance manager learning guide provides a wider context for evaluating training evidence. A software estimate that stays within its bounds is a useful result, but it is not an accredited qualification, a physical commissioning record or a verified occupancy audit.

Choose relevant simulator practice

Inspect the PLC curriculum overview for the product's current sequence of topics and access conditions. Compare its published objectives with the specific edge, boundary and reconciliation tests here. This article's full model is not claimed to be automatically graded there.

The sensor learning material is relevant when the meaning of a detection is unclear. Keep your own trace evidence independently of any product progress record and distinguish a simulated input from a measured installation signal.

Use the PLC programming examples collection to select your next project. Move to another state or sequence problem when you can explain why current input levels alone do not determine this counter's next value. That explanation is more useful than adding outputs without a new learning objective.

Conceptual PLC learning portfolio with a process sketch, test notes and a laptop showing logic
Conceptual learning illustration; not a validated circuit, program screenshot or physical test result.

Questions about PLC up/down counters

What happens if entry and exit arrive together?

This model combines the two fresh edges into a net change of zero before applying bounds. Your native instruction or another application may use a different policy. State it and test it, especially at zero and full.

Why not reset the counter whenever it looks wrong?

Resetting makes the stored estimate zero; it does not make the monitored area empty. A correction to an observed value needs a defined source, timing and event-handling policy. The reconciliation revision shows one explicit software rule.

Can the display say FULL when actual spaces remain?

A display can be consistent with its stored count while the count is inaccurate. This lesson verifies arithmetic from supplied events, not actual occupancy. Trace the input meaning and rejected or missed events separately.

What should I ask an AI tutor to calculate?

Provide Count zero, the previous input pair and the current input pair. Ask it to calculate each edge, Delta and the clamped result. Then ask it to compare subtract-then-add with net-change-before-clamp at the boundary. Check the intermediate values yourself rather than accepting a general claim that up and down always cancel.

By PLC Programming SA · Last updated 2026-09-11