PLC Programming SAPLC ProgrammingSOUTH AFRICA
Menu

exercises · South Africa

PLC Traffic Light Program: States, Timers and Restart

Build a PLC traffic light program with clear state transitions, timing traces and restart tests, plus ladder logic guidance for South African learners.

Conceptual PLC traffic light program study desk with a red signal model, controller trainer and laptop
Conceptual learning illustration; not a validated circuit, program screenshot or physical test result.

This PLC traffic light program is a virtual sequencing exercise: Red for a nominal 12 seconds, Green for 10, Amber for 3, then back to Red. You will define startup, disabling, late evaluations and invalid-state recovery before translating the sequence into ladder logic or structured text.

The three outputs are programme indicators. This is not a design for controlling a road, quarry access lane, pedestrian crossing or vehicle movement. A red Boolean does not prove that a physical red lamp is visible, that another approach is stopped or that a route is clear. The fictional durations teach sequence logic; they are not traffic-engineering recommendations.

For South African students, electricians and adult learners comparing PLC courses, the exercise is useful because its output is easy to visualise while its timing details still require careful reasoning. The target is an explainable trace, not simply an animation that cycles through familiar colours.

Write the state table before the rungs

Use one State variable with four allowed values: Disabled, Red, Green and Amber. AutoOn is a supplied Boolean. CurrentTimeMs is a supplied, nondecreasing whole-number timestamp in milliseconds. PhaseStartedAt records the timestamp at which the current enabled phase was entered.

The exercise uses fixed positive phase durations. Do not add editable presets until you have specified what zero, negative, out-of-range or mid-phase changes should mean. Keeping those values fixed makes the first sequence easier to test without pretending that parameter validation is unnecessary in a larger programme.

State after evaluationRedIndicatorGreenIndicatorAmberIndicatorNext timed phase
DisabledFalseFalseFalseNone
RedTrueFalseFalseGreen after 12000 ms
GreenFalseTrueFalseAmber after 10000 ms
AmberFalseFalseTrueRed after 3000 ms

AutoOn false selects Disabled and clears PhaseStartedAt. On an enabled evaluation starting from Disabled, enter Red and set PhaseStartedAt to the current timestamp. This gives the restarted Red phase its own full interval instead of reusing elapsed time from the interrupted phase.

Initialise State to Disabled and PhaseStartedAt empty whenever you start a fresh exercise run. If AutoOn is already true on the first evaluation, that evaluation enters Red. This is an explicit initialisation rule, not a prediction about a particular controller’s retained memory after power loss.

If state memory and output conditions are unfamiliar, work through ladder logic basics first. The start-stop exercise provides a simpler comparison between an input request and retained programme state.

Process one transition per evaluation

Read the state that exists at the beginning of the evaluation. Apply one priority decision to choose the next state, then calculate the outputs from that resulting state. Do not repeatedly evaluate the new state until several transitions have occurred.

The priority order is: disable first; initialise or recover second; process one timed transition third. If AutoOn is false at the exact instant a phase would otherwise expire, disable wins. The model does not briefly select the next enabled colour before blanking its virtual indicators.

For an enabled valid phase, calculate elapsed time as CurrentTimeMs minus PhaseStartedAt. When elapsed time reaches or exceeds that phase’s duration, advance once and set PhaseStartedAt to CurrentTimeMs. Otherwise retain both state and timestamp.

An unexpected State value is handled explicitly. While enabled, select Red, store the current timestamp and report InvalidStateDetected for that evaluation. While disabled, the disable branch remains dominant. In this exercise the diagnostic is an observation, not a latched alarm with a separate acknowledgement policy.

That recovery prevents an unknown state value from leaving this model without a defined next step. It does not establish that Red is a physically safe fallback for every installation. The exercise controls virtual indicators and has no information about external equipment or vehicle positions.

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.

A structured-text-style description of the algorithm

The following is language-neutral pseudocode written in a structured-text style. State names, timestamp storage and duration lookup are abstract helpers. Before using an actual controller, choose supported types, clock facilities and initialisation methods from that environment’s documentation.

InvalidStateDetected := FALSE;
OldState := State;

IF NOT AutoOn THEN
    State := Disabled;
    PhaseStartedAt := EMPTY;
ELSIF OldState = Disabled THEN
    State := Red;
    PhaseStartedAt := CurrentTimeMs;
ELSIF OldState NOT IN {Red, Green, Amber} THEN
    State := Red;
    PhaseStartedAt := CurrentTimeMs;
    InvalidStateDetected := TRUE;
ELSIF CurrentTimeMs - PhaseStartedAt >= DurationOf(OldState) THEN
    State := NextPhaseOf(OldState);
    PhaseStartedAt := CurrentTimeMs;
END_IF;

RedIndicator   := AutoOn AND (State = Red);
GreenIndicator := AutoOn AND (State = Green);
AmberIndicator := AutoOn AND (State = Amber);

DurationOf returns 12000, 10000 or 3000 for Red, Green or Amber. NextPhaseOf maps Red to Green, Green to Amber and Amber to Red. These mappings are fixed for this exercise. All three output assignments occur after state selection and each output has one writer in the model.

The pseudocode assumes a valid timestamp is associated with every valid enabled phase. Do not manually force State to Green while leaving its timestamp empty and then claim to have tested normal startup. If you permit arbitrary state editing in a training interface, define how that interface validates or repairs the complete state record.

A falling AutoOn value does not need an edge detector here: its false level selects Disabled on every disabled evaluation. An enabled evaluation from Disabled begins Red once. Remaining enabled does not continuously reset the Red timestamp because State is no longer Disabled.

Translate the decision order into ladder logic

In ladder logic, keep the same three responsibilities visible: state selection, time comparison and output decoding. It can help to maintain CurrentState and NextState separately during an evaluation, then commit NextState once before the output rungs.

Start by copying CurrentState to NextState. A disable branch chooses Disabled. An enabled start or invalid-state branch chooses Red and a new timestamp. Timed branches use comparisons against CurrentState, not a partially updated NextState. Each accepted transition also requests the new phase-start timestamp.

Give competing branches explicit priority. Merely placing several MOVE instructions on separate rungs does not explain what happens when more than one condition is true. A later write can replace an earlier result. Record which rung owns the final state assignment and test the exact boundary conditions.

Decode the resulting state into the three virtual indicators after the commit. Do not mix old-state and new-state comparisons across different output rungs. Within this model, comparing one final state value against three distinct values means at most one indicator is true.

That logical exclusivity does not prove physical output update simultaneity, lamp health or absence of other programme writers. When evaluating a native project, inspect where else the tags are assigned and how the task and output system operate. For this exercise, keep the outputs in a watch table or disconnected simulation.

The scan-cycle lesson is a useful next reading topic. You can also inspect PLC Simulation Software’s scan-cycle highlighting feature when comparing execution order with what appears on screen.

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.

Why a self-resetting TON is a different timing model

A native on-delay timer can support a sequencing exercise, but it needs defined invocation and reset behaviour. The CODESYS TON documentation describes an input edge starting the delay, a falling edge resetting it and Q becoming true after the configured interval while IN remains true.

Schneider Electric’s TON documentation likewise describes elapsed time and the relationship between IN, Q and the preset. Use the exact instruction documentation when choosing a native implementation. A textbook timer symbol alone does not identify every execution detail.

Consider a pattern that calls a timer with IN := AutoOn AND NOT PreviousTimerQ. If Q became true on the previous evaluation, the next call receives false and resets it. Another evaluation may be needed to start the following interval. That reset/start overhead is not represented by simply adding the three presets.

The timestamp model on this page instead starts the next phase’s interval at the evaluation that enters that phase. The two approaches can produce different observed cycle lengths. Neither difference should be hidden by claiming both implementations produce exactly the same timing without a trace.

If you implement a timer-based version, log the value of Q before the call, IN passed to the call, Q afterwards, elapsed time and State. Test more than one cycle. A first successful transition cannot prove that the timer is reset correctly for every subsequent phase.

The flashing-beacon timer exercise examines feedback through previous timer outputs. Use it to study that pattern separately before combining it with a three-phase state machine.

Follow a complete cycle at the boundaries

Start a fresh run with AutoOn true at time zero. The table deliberately includes evaluations immediately before and at the phase thresholds. These are supplied observations, not measurements of a browser frame rate or an actual PLC task.

CurrentTimeMsState after evaluationPhaseStartedAtRedGreenAmber
0Red0100
11999Red0100
12000Green12000010
21999Green12000010
22000Amber22000001
24999Amber22000001
25000Red25000100
36999Red25000100
37000Green37000010

This trace returns to Red after 25000 ms because evaluations occur at all three exact thresholds. The sum of the configured intervals is also 25000 ms. Those facts do not guarantee that an arbitrary evaluation schedule will observe a 25-second cycle.

Keep phase elapsed time separate from total session time. At 25000 the total supplied time is 25 seconds, but the new Red phase’s elapsed time is zero. Reusing the session origin as the phase origin would immediately make later phase comparisons overdue.

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.

Test late evaluations without skipping colours

Now supply evaluations at 0, 11900, 12100, 22000, 22300, 25200 and 25400 ms. The first Green state is observed at 12100. Its own 10000 ms interval begins there. The evaluation at 22000 is therefore still Green; at 22300 the state becomes Amber.

Amber’s interval begins at 22300, so 25200 is still Amber and 25400 enters Red. The observed cycle is 25400 ms. This result follows from the chosen timestamps and the rule that each phase origin is its actual entry evaluation.

Test a much larger gap: start Red at zero, then evaluate at 60000. The model advances once to Green and records 60000 as the new origin. It does not replay an invisible Green and Amber interval to catch up with a presumed wall-clock schedule.

At 60001 it remains Green. At 70000 it enters Amber, and at 73000 it enters Red. This behaviour preserves an observed interval for each entered phase under the stated model. An absolute repeating schedule would be a different specification with different results after a long gap.

Do not turn these examples into a general statement that a PLC “loses” a fixed number of milliseconds per scan. The samples here are deliberately supplied values. Native task timing, timer resolution and screen updates require their own measurements and documentation.

Verify disabling, restarting and invalid state

Disable during Green at time 14000 in a normal first cycle. All three indicators become false and the timestamp is cleared. Enable again at 15000: State becomes Red with a new origin of 15000. It stays Red at 26999 and becomes Green at 27000.

Disabling exactly at a phase threshold also selects Disabled. Test that case for Red, Green and Amber, rather than assuming a test during one phase covers every branch. No timed transition should override the higher-priority disable decision.

Next supply an invalid state value while enabled. The exercise enters Red, records the current time and reports InvalidStateDetected for that evaluation. A following ordinary Red evaluation clears the diagnostic because it is not latched. If you want a persistent alarm, specify and test its acknowledgement rules separately.

Test a fresh run with AutoOn false for several evaluations. The model stays Disabled. When AutoOn eventually becomes true, Red starts at that evaluation’s timestamp. Time spent disabled must not count towards the Red interval.

For each test, save the inputs, previous state, resulting state, timestamp and three outputs. Mark expected and observed results separately. A screenshot of three coloured circles cannot demonstrate restart semantics or invalid-state recovery by itself.

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

Extend the learning model with clear new requirements

A second virtual signal face introduces a joint-state problem. Define a table of allowed output combinations for both faces, then verify that every transition selects one allowed combination. Do not create two independent repeating sequences and assume their colours will remain coordinated.

An all-red learning phase also needs an explicit purpose and fictional duration. Its presence does not establish adequate clearance for a real route. Keep any such extension disconnected and describe the programme states without claiming to calculate traffic safety from a timer preset.

A flashing mode introduces mode changes as well as phase changes. Decide whether entering or leaving it resets the normal sequence, whether the first flash starts on or off, and how disabling interrupts the flasher. The beacon exercise can supply a separate timing study, but its previous timer values must not accidentally control the normal sequence.

A pedestrian-request extension adds event memory. Decide whether one request is stored, repeated presses merge, held buttons create new requests, or requests during a service phase are deferred. The pedestrian crossing exercise is a follow-on topic; compare its declared scope before combining programmes.

Keep each extension as a version with a revised state table and its own tests. More states are not automatically deeper learning: the valuable part is being able to explain the new priority decisions and demonstrate their consequences.

Questions for a South African PLC training course

When comparing a course in Johannesburg, Pretoria, Durban, Cape Town or an online format, ask which programming environment the learner actually uses. The city name does not tell you whether a lesson includes ladder editing, structured text, timer observation or just a demonstration video.

Ask the provider to run the disable-at-threshold test and the late-evaluation example. It should be possible to explain whether the supplied implementation uses native timers, a simulated clock or an absolute schedule. A different implementation is reasonable when its assumptions and results are made clear.

For a portfolio, keep a one-page state table, the normal boundary trace, one interrupted run and one corrected defect. Describe it as a simulated PLC sequence exercise. A course completion record does not turn it into a commissioned traffic-control project or a registered qualification.

Use the online PLC training guide to compare delivery arrangements, or the engineering-student learning guide to plan evidence you can explain. Choose the next lesson around the skill you still cannot demonstrate, rather than repeating the same animation with a different page title.

Common questions about PLC traffic-light sequencing

Is the total cycle exactly 25 seconds?

The configured intervals total 25 seconds. The worked boundary trace observes that total because evaluations occur at the thresholds. With later observations, this model enters phases later and the observed cycle can be longer. Report the actual trace alongside the nominal settings.

Why use one state instead of three latches?

One state makes the allowed colour combination explicit. Three separately retained outputs require additional rules to clear the old output and prevent overlap. A state variable still needs correct decoding, initialisation and ownership; its existence alone is not a proof that an entire project is correct.

Should disabling leave the virtual red indicator on?

This exercise specifies all indicators false while disabled. Another exercise could specify red while disabled, but that changes the output contract and tests. Neither choice here determines the correct physical response for a road or machine installation.

Can I use a phone stopwatch to verify the programme?

A stopwatch can help notice a gross duration error, but it does not replace the state and timestamp trace. Display refresh, human reaction and the execution environment affect what you observe. Use internal records to explain the exact model transitions, and identify what your measurement actually covers.

Does this programme control an actual intersection?

No. It is a disconnected, single-face teaching sequence with fictional durations. It contains no validated conflict monitoring, physical lamp feedback, route design or implementation for real traffic. Its learning value is in state transitions, timing and test design.

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.

Compare the lesson with a simulator scenario

Open the traffic-light PLC scenario preview in PLC Simulation Software to inspect that product’s related practice entry point. Compare its actual transition order, controls and access information with the contract on this page; do not assume its implementation or durations are identical.

The PLC programming examples collection links this exercise to other timing and memory problems. Move on when you can predict a boundary transition, explain an interrupted run and distinguish the programme’s requested indicator state from evidence about physical equipment.

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