Bottling Line PLC Programming: Sequence, Tracking & CIP
A vendor-neutral bottling-line control example covering state machines, station handshakes, filling, tracking, recipes, inspection, CIP and commissioning.
A reliable bottling-line PLC program separates line coordination, machine-module control, product tracking, quality decisions and safety. Each station owns its local actuators and faults; a line coordinator exchanges clear ready/running/starved/blocked/fault states; product records follow bottles to inspection and rejection; recipes are versioned and validated; and CIP runs only from an approved process recipe.
This guide develops a vendor-neutral reference for a line containing an infeed, rinser, filler, capper, labeler, inspector and reject station. Adapt the pattern to the selected controller, machine builder, product, hygienic design and site standards. It is not a commissioning package or a validated food-safety or machinery-safety design.

1. Start with the Line Contract
Do not begin by writing individual motor rungs. Define the boundaries between the line coordinator and each machine.
Reference process flow
- Empty containers enter and are spaced.
- A rinser or cleaning station prepares them where required.
- The filler dispenses the selected product.
- The capper applies and verifies the closure.
- The labeler applies product identification.
- Inspection checks required quality attributes.
- A reject mechanism removes a failed container.
- Accepted product continues to secondary packaging.
Each module should expose a small, documented state contract:
| Signal | Owner | Meaning |
|---|---|---|
Ready |
Machine | Able to accept a start/request |
Running |
Machine | Executing its automatic cycle |
Starved |
Machine | Cannot run because upstream product is absent |
Blocked |
Machine | Cannot discharge because downstream is unavailable |
Faulted |
Machine | Requires defined recovery or intervention |
RequestRun |
Line coordinator | Production is requested for this module |
LineSpeedRef |
Line coordinator | Approved line reference, not a raw actuator command |
RecipeId / RecipeVersion |
Recipe manager | Validated product setup requested |
Complete |
Machine | Requested transition or cycle completed |
The exact state model may follow an organization’s PackML implementation or another documented standard. The important feature is one meaning per signal. Avoid a single “healthy” bit that silently combines safety, mode, material, quality and downstream availability.
2. Define Safety and Process Boundaries
The standard PLC can coordinate production behavior, but safety-related functions require a risk assessment, suitable safety-rated architecture and validation by qualified people.
Typical boundaries include:
- Emergency stop and guard protection
- Safe torque off or safe stop of drives
- Unexpected restart prevention
- Trapped-energy and pneumatic hazards
- Safe access to rotary fillers, cappers and conveyors
- Chemical, pressure and temperature hazards during cleaning
The production program may observe validated safety status and move to a defined non-production state. It must not bypass or recreate the safety function in ordinary logic.
Likewise, this guide does not prescribe universal CIP chemicals, concentrations, temperatures or durations. Those values belong to a validated hygienic process created for the actual product, soil, materials, equipment and regulatory system.
3. Use an Explicit Line State Machine
Avoid hundreds of unrelated permissive contacts controlling a shared run bit. An explicit state machine makes startup, starvation, blocking, recovery and abort behavior testable.

One practical line-level model is:
| State | Purpose | Typical exit |
|---|---|---|
STOPPED |
Stable non-production state | Start request with all prerequisites |
STARTING |
Start utilities and machines in the approved order | All required modules running |
RUNNING |
Normal production | Hold, suspend, stop, abort or fault |
HELD |
Controlled operator-requested pause | Resume request |
STARVED |
Upstream product unavailable | Product restored and debounce complete |
BLOCKED |
Downstream cannot accept product | Capacity restored and debounce complete |
STOPPING |
Controlled empty/stop sequence | All modules stopped |
FAULTED |
Production fault requires recovery | Fault cleared and reset conditions met |
ABORTING |
Rapid controlled production abort | Defined abort actions complete |
CIP |
Approved cleaning sequence owns relevant equipment | CIP completion and release |
Vendor-neutral Structured Text skeleton
CASE LineState OF
STOPPED:
RunRequest := FALSE;
IF StartPB AND AutoMode AND LinePermissive AND RecipeApproved THEN
LineState := STARTING;
END_IF;
STARTING:
RunRequest := TRUE;
IF AnyCriticalFault THEN
LineState := FAULTED;
ELSIF AllRequiredModulesRunning THEN
LineState := RUNNING;
ELSIF StartTimeout.Q THEN
CaptureFirstOutFault();
LineState := FAULTED;
END_IF;
RUNNING:
RunRequest := TRUE;
IF AbortRequest OR SafetyUnavailable THEN
LineState := ABORTING;
ELSIF StopPB THEN
LineState := STOPPING;
ELSIF DownstreamBlocked THEN
LineState := BLOCKED;
ELSIF UpstreamStarved THEN
LineState := STARVED;
ELSIF AnyCriticalFault THEN
LineState := FAULTED;
END_IF;
STARVED:
RunRequest := TRUE; // Module policy decides which sections coast or hold.
IF NOT UpstreamStarved AND StarveClearDebounce.Q THEN
LineState := RUNNING;
ELSIF StopPB THEN
LineState := STOPPING;
END_IF;
BLOCKED:
RunRequest := TRUE;
IF NOT DownstreamBlocked AND BlockClearDebounce.Q THEN
LineState := RUNNING;
ELSIF StopPB THEN
LineState := STOPPING;
END_IF;
STOPPING:
RunRequest := FALSE;
IF AllModulesStopped THEN
LineState := STOPPED;
END_IF;
FAULTED:
RunRequest := FALSE;
IF ResetPB AND FaultResetAllowed THEN
ClearResettableFaults();
LineState := STOPPED;
END_IF;
ABORTING:
RunRequest := FALSE;
IF AbortActionsComplete THEN
LineState := STOPPED;
END_IF;
END_CASE;
This is an illustrative pattern. Whether a blocked or starved module continues, slows, empties or stops depends on the mechanical design and approved operating specification.
4. Coordinate Machines Without Oscillation
Fast changes in photoeyes or accumulation sensors can make adjacent machines repeatedly start and stop. Use:
- Separate enter and clear thresholds
- On-delay/debounce timers justified by measured mechanics
- Minimum run and minimum stop policies where permitted
- A defined downstream-to-upstream stop order
- A defined upstream-to-downstream startup order
- A first-out reason explaining the transition
For every machine pair, test:
- Downstream stops normally.
- Downstream faults while product is transferring.
- Upstream starves.
- The line stops with product between stations.
- Power or communications returns with product still present.
Do not let both machines infer the other’s intent from motor feedback alone. Exchange explicit state and acceptance signals.
5. Filling Control: Choose the Measurement First
The filling algorithm depends on how volume or mass is measured.

| Method | Control evidence | Common PLC responsibility |
|---|---|---|
| Timed fill | Qualified flow stability and periodic checks | Valve timing, timeout and drift monitoring |
| Flowmeter | Totalized or instantaneous flow | Fast/slow cutoff, total verification and no-flow fault |
| Load cell | Stable tare and weight | Tare, coarse/fine fill, settle and tolerance check |
| Level fill | Physical level reference | Container presence, valve sequence and overflow prevention |
| Counter-pressure process | Pressure and valve-state feedback | Purge/pressurize/fill/depressurize sequence |
A head-level filling state machine
EMPTY
-> BOTTLE_CONFIRMED
-> TARE_OR_PREPARE
-> FAST_FILL
-> FINE_FILL
-> SETTLE
-> VERIFY
-> RELEASE
Any state -> FAULT when:
- bottle is lost
- no flow is detected
- maximum fill time expires
- measurement is invalid
- valve feedback disagrees
Use an explicit maximum time and maximum allowed quantity independent of the normal cutoff. Record the measurement used for the accept/reject decision, its units, recipe version and calibration status.
Illustrative fill logic
CASE FillState OF
WAIT_BOTTLE:
IF BottleClamped AND MeasurementHealthy THEN
FillTotal := 0.0;
FillState := FAST_FILL;
END_IF;
FAST_FILL:
FastValve := TRUE;
IF FillTotal >= Recipe.FastCutoff THEN
FastValve := FALSE;
FillState := FINE_FILL;
ELSIF FillTimeout.Q OR NOT BottleClamped THEN
FillState := FILL_FAULT;
END_IF;
FINE_FILL:
FineValve := TRUE;
IF FillTotal >= Recipe.Target THEN
FineValve := FALSE;
FillState := SETTLE;
ELSIF FillTimeout.Q OR NOT BottleClamped THEN
FillState := FILL_FAULT;
END_IF;
SETTLE:
IF SettleTimer.Q THEN
FillAccepted :=
(FillTotal >= Recipe.AcceptLow) AND
(FillTotal <= Recipe.AcceptHigh);
FillState := COMPLETE;
END_IF;
FILL_FAULT:
FastValve := FALSE;
FineValve := FALSE;
FillAccepted := FALSE;
END_CASE;
The real program must address measurement quality, valve response, physical overfill protection, hygienic design and the selected equipment’s documented behavior.
6. Track Each Bottle to the Correct Reject
A reject command is useless if it reaches the wrong bottle. Tracking should survive normal gaps, controlled stops and speed changes.

Product record
TYPE BottleRecord :
STRUCT
Valid : BOOL;
TrackingId : DINT;
RecipeId : DINT;
RecipeVersion : DINT;
FillValue : REAL;
FillPass : BOOL;
CapPass : BOOL;
LabelPass : BOOL;
VisionPass : BOOL;
RejectRequired : BOOL;
RejectReason : DWORD;
END_STRUCT
END_TYPE
Possible tracking methods:
- Indexed position array: good where discrete pitches are mechanically fixed
- Encoder-distance tracking: good for continuous conveyors with position windows
- Carrier/puck ID: useful where products remain associated with known carriers
- Vision or code identity: useful where item identity must persist across stations
Tracking acceptance tests
- One intentional bad bottle is rejected, and adjacent bottles pass.
- A gap does not create a phantom record.
- A controlled stop before the reject preserves identity.
- Encoder reset or rollover is handled.
- A bottle removed manually is reconciled under procedure.
- Communications loss marks affected results invalid rather than “pass.”
- The reject device proves actuation or raises a reject-not-confirmed fault.
Never shift a record purely every PLC scan. Shift or update from a qualified physical event: pitch pulse, carrier index, registered encoder window or verified transfer.
7. Capping, Labeling and Inspection
Each station should distinguish command issued, device completed and quality result.
Capper
Record the evidence available from the actual capper:
- Bottle present and stable
- Cap available/present
- Application cycle complete
- Torque/angle result if supplied by the device
- Cap inspection result
- Reject reason if not accepted
Do not infer acceptable torque solely from a motor-running bit.
Labeler
The PLC normally coordinates:
- Product trigger or registration
- Recipe/product code
- Applicator ready and fault state
- Label-present or print verification
- Reject association
The exact positioning loop may live inside the labeler controller. Define ownership so that two controllers do not fight over registration.
Vision and inspection
Use an explicit transaction:
- PLC asserts a trigger with a tracking ID or known position.
- Vision system acknowledges the trigger.
- Vision system returns result-valid plus detailed results.
- PLC associates the result with the bottle record.
- Timeout or mismatched sequence number becomes “inspection invalid,” not “pass.”
The HMI should expose the failed criterion, image/reference where available, threshold/recipe version and reject confirmation.
8. Recipes and Changeover
A recipe is controlled production configuration, not an arbitrary group of writable HMI tags.

Recommended fields include:
- Product and container identifier
- Recipe version and approval state
- Target/cutoff/tolerance values with units
- Valid line-speed range
- Station enable/bypass policy
- Servo or guide positions where engineered
- Cap, label and inspection product codes
- CIP release/compatibility identifier
- Change author, reviewer and effective date
Changeover transaction
- Stop or empty the line according to procedure.
- Select the candidate recipe.
- Validate ranges and machine compatibility.
- Command participating machines to load the same recipe ID/version.
- Collect load acknowledgements.
- Perform required mechanical checks.
- Run first-article production.
- Confirm inspection and quality approval.
- Release full production.
If one station reports a different version, block automatic start and show exactly which station disagrees.
9. Motion and Registration
High-speed bottling equipment may use coordinated axes for star wheels, carousels, screws, label feeds, cappers or inspection triggers. The PLC program must define:
- Master position and units
- Gear/cam relationships
- Homing and reference procedure
- Engage/disengage conditions
- Registration correction limits
- Response to encoder, following or drive fault
- Recovery when product remains in the machine

Never copy a universal gear ratio or cycle time from an article. Derive it from the machine geometry and validate it under the motion supplier’s documented limits.
10. CIP Integration Without Unsafe Universal Recipes
CIP programming coordinates a validated cleaning recipe; it does not invent the cleaning process.
The controls layer may manage:
- Equipment allocation and route selection
- Valve-position verification
- Pump permissives and flow proof
- Temperature, conductivity or concentration instrumentation
- Step transition criteria
- Diversion and return routing
- Chemical/utility availability
- Deviations, holds and abort behavior
- Batch record and audit trail
Safe control pattern
Each phase should have:
- Entry conditions
- Commanded route and equipment
- Independent proof conditions
- Minimum/maximum limits from the approved recipe
- A deviation response
- Completion criteria
- Recorded actual values
Production and CIP ownership must be mutually exclusive for shared equipment. Transition back to production only after the validated sequence completes, equipment is released, required checks pass and the responsible procedure authorizes it.
Follow the site’s approved sanitation program, chemical safety data, hygienic design, food-safety plan and applicable regulation. Values differ by product and equipment; a generic web recipe is not validation.
11. Complete Example Architecture
Controller responsibility
Line coordinator
├── Production state and mode
├── Recipe transaction
├── Starved/blocked propagation
├── Production counts and reason codes
└── Historian/MES interface
Machine modules
├── Infeed and spacing
├── Rinser
├── Filler
├── Capper
├── Labeler
├── Inspector/reject
└── Outfeed/packer interface
Independent or safety-rated systems as required
├── Machinery safety functions
├── Vision processor
├── Motion/drive functions
└── Validated CIP/process instrumentation
Program organization
| Program/module | Responsibility |
|---|---|
PRG_LineState |
Line transitions and first-out reasons |
PRG_Handshake |
Machine-state exchange and timeouts |
PRG_Recipe |
Validate, distribute and confirm version |
PRG_Tracking |
Create, move and reconcile bottle records |
PRG_Quality |
Combine station results and reject reasons |
PRG_CIP_Interface |
Exchange approved CIP ownership/status |
PRG_Alarms |
Alarm conditions, delay, latch and reset policy |
PRG_Data |
Counts, events and reporting interface |
Useful diagnostic fields
- Current and previous line state
- State-entry timestamp
- Transition reason
- First-out fault
- Active recipe/version by station
- Last good transfer per machine pair
- Tracking count at each zone
- Last rejected tracking ID/reason
- Safety available/status summary
- CIP owner, step and deviation summary
12. FAT and Commissioning Test Matrix
Test from requirements, not from the programmer’s memory.
| Test | Method | Expected result |
|---|---|---|
| Normal start | All prerequisites valid, request auto start | Defined startup order; running state reached |
| Start timeout | Hold one required ready signal false | Start fails with the correct first-out reason |
| Upstream starvation | Remove qualified infeed product | Defined starved behavior; clean recovery |
| Downstream blockage | Block acceptance downstream | Defined accumulation/stop behavior; no collision |
| Fill no-flow | Command fill with no qualified flow | Valves close; bottle fails; diagnostic identifies no-flow |
| Inspection timeout | Suppress result-valid | Product is not marked pass; correct reject/hold action |
| Tracking stop/restart | Stop before reject with bad product present | Same product is rejected after restart |
| Recipe mismatch | One station retains old version | Automatic start inhibited with station identified |
| Communications loss | Disconnect a representative device | Defined equipment response and recovery |
| Power recovery | Restore after controlled test state | No unexpected automatic movement; records reconciled |
| Reject confirmation | Prevent reject actuator proof | Reject-not-confirmed alarm and specified line response |
| CIP ownership | Request production while CIP owns equipment | Production start inhibited |
Also test boundaries around counters, arrays, encoder rollover, maximum product queue, invalid analog quality, simultaneous faults and alarm floods.
13. HMI and Data That Help Operators
The main line view should answer:
- What state is the line in?
- Why is it not running?
- Which station is starved, blocked or faulted?
- What must happen next?
- Which recipe/version is active?
- Where is rejected or unverified product?
Use first-out and transition history rather than presenting hundreds of equally styled alarms. Trend fill measurement and reject reason by station, but make clear whether values are raw, corrected, accepted or invalid.
For OEE, define availability, performance and quality rules with operations before coding. Planned downtime, small stops, rework and quality holds must have agreed classifications; otherwise the percentage is not comparable.
Practise the Sequence Before Vendor Implementation
Use a simulator to rehearse state logic, timers, interlocks and recovery before mapping the design to vendor-specific instructions. Ownership disclosure: PLCProgramming.io and PLC Simulation Software are operated by the same publisher. The browser product is useful for learning control patterns but is not a bottling-line digital twin, safety validator, hygienic-process validator or replacement for target hardware testing.
Frequently Asked Questions
What PLC is best for a bottling line?
Select from the customer standard, required motion/safety/network functions, qualified machine modules, local support, lifecycle plan and tested performance. A brand-only answer ignores the actual architecture.
How do you synchronize machines in a bottling line?
Exchange explicit machine states and transfer permission, then use the appropriate mechanical, encoder or motion reference for product movement. Test starved, blocked, fault and stop/restart behavior at every boundary.
How should bottles be tracked?
Create a product record at a qualified entry event and move it using a verified pitch, encoder window, carrier ID or transfer event. Associate every quality result and reject with that record, and test gaps and restarts.
How do you program bottle filling?
Choose the physical measurement method first, then implement explicit prepare, fast-fill, fine-fill, settle, verify and fault states with independent maximum-time/quantity protection.
How should CIP be programmed?
Automate only an approved and validated cleaning recipe. Prove route, valve state, flow and other required conditions; record actuals and deviations; maintain exclusive ownership between production and CIP.
What is the difference between starved and blocked?
Starved means the machine lacks acceptable upstream product. Blocked means downstream cannot accept discharge. They require different propagation and recovery behavior.
Should an E-stop be programmed in the standard PLC?
No. Machinery safety functions require a suitable risk-assessed, safety-rated and validated implementation. Ordinary PLC logic may monitor the resulting status for production-state handling.
Primary References
- IEC 61131-3 programmable controller languages
- OMAC PackML resources
- FDA: Current Good Manufacturing Practice, Hazard Analysis, and Risk-Based Preventive Controls for Human Food
- EHEDG hygienic engineering guidance
- OSHA: Control of hazardous energy
This engineering guide was reviewed on July 25, 2026. Validate all vendor, machine, product, safety and sanitation requirements against the current primary documentation for the installed line.
Next Step
Start with one machine boundary: document its Ready, RequestRun, Running, Starved, Blocked, Faulted and recovery behavior. Build the line state model and FAT tests before adding high-speed detail.
Continue with the packaging machine PLC guide, conveyor PLC programming guide, PLC state-machine reference, high-performance HMI guide and industrial communications guide.


