Programming Guides14 min read12 870 words

Bottling Line PLC Programming: Complete Guide to Beverage Production Automation

Master bottling line PLC programming with this comprehensive guide covering filling, capping, labeling, vision inspection, CIP, and high-speed beverage automation.

IAE
Senior PLC Programmer
15+ years hands-on experience • 50+ automation projects completed
PLC
Programming Excellence
🚧 COMING DECEMBER 2025

🎯 Master PLC Programming Like a Pro

Preorder our comprehensive 500+ page guide with real-world examples, step-by-step tutorials, and industry best practices. Everything you need to become a PLC programming expert.

  • ✓ Complete Ladder Logic Programming Guide
  • ✓ Advanced Function Block Techniques
  • ✓ Real Industrial Applications & Examples
  • ✓ Troubleshooting & Debugging Strategies
60% Off Preorder
$47
vs $127 Final Price
Preorder Now

📋 Table of Contents

This comprehensive guide covers:

  • Introduction to PLC Programming Fundamentals
  • Understanding Ladder Logic Programming
  • Function Block Diagrams and Structured Text
  • Advanced Programming Techniques
  • Real-World Application Examples
  • Troubleshooting and Best Practices
  • Industry Standards and Compliance
  • Career Development and Certification Paths

Introduction: Engineering High-Speed Beverage Production Automation

Bottling line automation represents the pinnacle of high-speed PLC programming, where precision control meets extreme throughput demands. Modern beverage production facilities operate at staggering speeds exceeding 72,000 bottles per hour (1,200 BPH), requiring sophisticated PLC programming that orchestrates synchronized motion, precise filling control, quality inspection, and hygienic process management. This comprehensive guide equips beverage industry engineers, bottling plant operators, and OEM machine builders with the specialized knowledge needed to design, program, and optimize complete bottling line automation systems from raw bottle infeed through final case packing.

The beverage industry faces unique automation challenges that distinguish bottling applications from general packaging operations. Lightweight plastic bottles requiring gentle air conveying to prevent deformation, rotary filling machines with 12-72 filling heads demanding precise electronic synchronization, clean-in-place (CIP) systems maintaining sanitary conditions between product runs, and stringent quality requirements ensuring every bottle meets fill level, cap torque, and labeling standards all contribute to programming complexity. Successful bottling automation engineers must master coordinated multi-machine control, high-speed product tracking, electronic filling algorithms, and regulatory compliance requirements specific to food and beverage manufacturing.

Understanding bottling line PLC programming creates career opportunities with major beverage companies including Coca-Cola, PepsiCo, Anheuser-Busch InBev, Nestlé Waters, and countless regional bottlers operating thousands of production facilities globally. Equipment manufacturers including Krones, Sidel, KHS, Sacmi, and Ronchi supply sophisticated bottling machinery requiring skilled programmers for installation, commissioning, and ongoing optimization. The global beverage industry exceeds $1.5 trillion annually with continuous investment in automation technology driving demand for engineers combining PLC programming expertise with beverage application knowledge.

This tutorial covers everything from bottling line layout and PLC architecture selection through bottle handling systems, rotary filler programming, capping and labeling automation, vision inspection integration, CIP sequence control, and complete integrated line examples. You'll learn programming techniques for air conveyor pressure management, electronic filling valve control, star wheel synchronization, product tracking from infeed through packing, and OEE optimization specific to beverage production. By mastering these specialized bottling automation skills, you'll possess the expertise to tackle any beverage production automation challenge and deliver high-performance systems meeting demanding speed, quality, and efficiency requirements.

Chapter 1: Bottling Line Overview and Process Flow

Understanding Complete Bottling Line Architecture

Modern bottling lines integrate multiple machines in precisely coordinated sequences transforming empty bottles into filled, capped, labeled, inspected, and packaged products ready for distribution. Understanding the complete process flow, machine interactions, and control coordination requirements provides the foundation for effective bottling line PLC programming.

Depalletizer and Bottle Infeed Systems

Automated depalletizers remove empty bottles from incoming pallets, separating layers using vacuum or magnetic grippers and transferring bottles to infeed conveyors. This initial stage determines maximum line speed as downstream equipment must handle the continuous bottle stream without accumulation or starvation.

PLC programming controls layer picking sequences, pallet height tracking as layers are removed, empty pallet discharge, and bottle orientation verification ensuring all bottles enter the line in correct positions. Bottle counting from depalletizer establishes the reference count for tracking throughout production, enabling accurate inventory management and production reporting.

Accumulation tables between depalletizer and rinser provide buffering capacity absorbing upstream variations and maintaining steady bottle flow to downstream equipment. Air conveyor systems using low-pressure air cushions transport lightweight PET bottles without mechanical contact that could cause surface damage or deformation. Programming manages air pressure regulation adapting to different bottle weights and geometries while monitoring pressure zones to detect jams or unusual resistance indicating equipment problems.

Bottle Rinser and Washing Systems

Rinsers invert bottles and spray internal surfaces with filtered water or sanitizing solution removing dust, debris, and contaminants before filling. Rotary rinsers use continuous motion with bottles gripped on rotating turrets, while linear rinsers use intermittent indexing for lower speed applications.

Rinser programming coordinates gripper actuation timing synchronized with bottle infeed, inversion mechanisms positioning bottles upside-down over rinse stations, spray valve control with programmable duration and pressure, drainage time allowing rinse water to evacuate before re-inversion, and gentle bottle release onto outfeed conveyors. Critical programming considerations include preventing water carryover that would contaminate subsequent bottles and ensuring complete drainage before bottles enter the filling area.

Water quality monitoring integrates into control systems through conductivity sensors, pressure transducers, and flow meters ensuring rinse water meets specifications. Alarms trigger when parameters deviate from acceptable ranges, preventing contamination of bottle interiors that would compromise product quality and consumer safety.

Filling Machine Types and Configurations

Filling equipment selection depends on product characteristics, production speed requirements, and accuracy needs. Understanding filling machine principles guides appropriate PLC programming strategies for each configuration.

Gravity fillers use height differential between product reservoir and bottle opening, filling bottles to consistent levels based on liquid physics. Simple and reliable for still beverages, gravity filling suits applications where high speed and moderate accuracy suffice. Programming controls fill valve opening synchronized with bottle position, fill time duration allowing adequate flow, and valve closing preventing overflow or dripping.

Pressure fillers apply positive pressure forcing product into bottles faster than gravity alone permits. Counter-pressure fillers used for carbonated beverages pre-pressurize bottles with CO2 before filling, preventing foaming and carbonation loss. Programming manages complex valve sequencing including bottle pressurization, fill valve opening under controlled pressure differential, fill level sensing, valve closing, and depressurization before bottle release.

Volumetric fillers using piston-cylinder mechanisms or flow meters provide the highest accuracy by dispensing precise product volumes regardless of container variations. Electronic piston fillers use servo-driven pistons with programmable stroke lengths calculating exact volume delivery. PLC programming coordinates servo positioning, product valve timing, and multi-head synchronization for rotary volumetric fillers with 12, 24, or more filling heads.

Rotary Filling Machine Architecture

High-speed bottling lines predominantly use rotary filling machines where bottles transfer onto rotating carousels through star wheels, advance through filling positions during rotation, and discharge onto outfeed conveyors after filling completion. This continuous motion architecture maximizes throughput while maintaining gentle bottle handling.

Rotary filler programming manages several critical control zones. The infeed star wheel synchronizes bottle entry from linear conveyor to rotating carousel using electronic gearing matching linear and rotary velocities at the transfer point. Filling heads positioned around the carousel periphery execute filling sequences as bottles rotate beneath them. The discharge star wheel transfers filled bottles back to linear outfeed conveyors for transport to capping operations.

Speed synchronization across all conveyor sections, star wheels, and the main carousel requires master-slave axis coordination where a virtual master axis representing line speed drives all physical axes through calculated electronic gear ratios. This architecture enables smooth speed changes propagating uniformly across all equipment maintaining proper bottle spacing and preventing collisions or gaps.

Capping Systems and Closure Application

Capping equipment applies closures (screw caps, crown caps, corks) to filled bottles and applies specified torque or compression ensuring proper sealing without damage. Capping machine complexity ranges from simple single-head cappers for low-speed operations to sophisticated rotary cappers with multiple capping heads operating synchronously.

Cap Sorting and Feeding Systems

Vibratory bowl feeders orient closures from bulk hoppers, using specially designed bowl tracks that progressively orient caps to consistent positions for pickup by cap chutes delivering closures to application heads. Alternative systems use cap elevators with mechanical or vision-guided orientation.

Programming monitors cap feeder operation detecting bowl level through sensors triggering automatic cap replenishment, verifying proper cap orientation preventing misfeeds, and controlling feeder vibration intensity optimizing feed rate. Low cap detection triggers operator alerts preventing line shutdown from cap starvation.

Cap presence verification before and after application uses photoelectric sensors or vision systems. Missing cap detection at the application point triggers head skipping preventing operation attempts without closures present. Post-application verification confirms cap presence and correct orientation before bottles advance to labeling.

Capping Head Control and Torque Management

Rotary capper programming coordinates gripper mechanisms securing bottles during cap application, cap placement mechanisms positioning closures on bottle openings, spinning heads applying rotational torque tightening threaded closures, and torque monitoring ensuring proper application force without overtightening causing damage or undertightening risking leakage.

Electronic torque monitoring measures actual applied torque through servo drive current sensing or dedicated torque transducers. Programming compares measured torque against acceptable ranges stored in product recipes, logging torque values for statistical process control and quality trending. Out-of-spec torque triggers reject diversion removing suspect bottles from the production stream.

Multi-head rotary cappers require synchronized positioning of all capping heads maintaining consistent angular spacing around the carousel. Electronic camming coordinates complex motion profiles including head lowering onto bottles, torque application during rotation, and head lifting after completion. Recipe parameters adjust timing, torque setpoints, and motion profiles accommodating different closure types and bottle specifications.

Induction Sealing and Tamper-Evident Application

Many beverage applications use induction sealing creating hermetic seals by melting foil liners onto bottle openings using electromagnetic induction heating. This process occurs after cap application, with bottles passing beneath induction coil stations generating high-frequency electromagnetic fields heating foil liners.

Programming controls induction seal power levels, bottle dwell time under coils, and temperature monitoring preventing overheating damage. Seal quality verification uses vision inspection or electrical continuity testing detecting incomplete seals or missing foil liners before bottles leave the capping area.

Labeling Systems and Product Decoration

Product labeling applies pressure-sensitive labels, wraparound paper labels, or shrink sleeves providing branding, regulatory information, and tamper evidence. Labeling automation requires precise registration control maintaining label placement accuracy despite line speed variations and bottle geometry tolerances.

Label Applicator Technologies

Pressure-sensitive labelers peel adhesive-backed labels from backing material and transfer them to bottles using applicator pads, blow-on systems, or tamp-down mechanisms. Servo-driven label feed synchronized with bottle conveyors ensures labels apply at proper positions regardless of bottle spacing variations or speed changes.

Wraparound labelers apply paper labels using adhesive or hot-melt glue, wrapping labels around container circumferences with precise overlap control. Rotary labelers handle high speeds through continuous motion, while linear labelers use intermittent indexing for lower throughput applications.

Shrink sleeve applicators slide pre-printed polymer sleeves over containers then pass them through steam or hot air tunnels shrinking sleeves tightly onto container surfaces. This decoration method provides 360-degree graphics and tamper evidence but adds process complexity requiring tunnel temperature control and shrink quality verification.

Electronic Label Feed Synchronization

Label applicator programming uses electronic gearing coordinating label feed servos with bottle conveyor position tracked through encoders. Gear ratio calculations account for label length, gap spacing between labels, and bottle spacing on conveyors ensuring proper registration.

Gear Ratio = (Label Length + Gap) / Bottle Spacing

For example, 150mm labels with 3mm gaps applied to bottles spaced 200mm apart requires gear ratio = (150 + 3) / 200 = 0.765:1. Programming implements this relationship through MC_GearIn function blocks engaging electronic gearing when bottles enter the labeling zone and disengaging between bottles conserving label material.

Label registration uses photoelectric sensors detecting marks printed on label backing or label edges. Registration control algorithms measure position error between expected and actual mark detection, adjusting electronic gear ratios or label feed position offsets correcting accumulated errors and maintaining placement accuracy.

Vision Inspection Integration

Automated inspection systems verify product quality, regulatory compliance, and customer specifications before bottles leave production lines. Vision systems, x-ray inspection, and specialized sensors check multiple quality parameters at production speed without slowing throughput.

Fill Level Inspection

Fill level inspection verifies proper product volume in each bottle preventing underfilling that violates regulations and overfilling that wastes product. Inspection technologies include vision systems analyzing liquid level height through transparent containers, x-ray systems measuring fill height independent of container transparency, and specialized optical sensors detecting liquid surfaces.

Vision-based fill inspection uses cameras imaging bottles backlit by uniform light sources, with image processing algorithms detecting liquid meniscus position and calculating fill height. Programming interfaces with vision processors through industrial Ethernet protocols receiving inspection results including measured fill height, pass/fail status, and reject reason codes.

Integration programming manages camera triggering synchronized with bottle position ensuring images capture at consistent locations, reject gate activation diverting bottles failing fill specifications, and data logging recording fill height statistics for SPC charting and quality trending. Statistical calculations identify process drift before systematic underfilling or overfilling develops.

Cap and Closure Inspection

Cap inspection verifies presence, proper orientation, correct cap type, and seal quality. Vision systems check cap presence and angular orientation detecting missing, crooked, or backwards caps. Specialized sensors verify tamper band integrity on screw caps and induction seal presence beneath closures.

Programming coordinates inspection timing with bottle flow, interprets multiple inspection results (cap present, correct orientation, band intact, seal verified) through logical AND operations generating overall pass/fail decisions, and manages reject mechanisms removing defective bottles. Quality reporting categorizes rejects by failure type enabling root cause analysis and corrective actions.

Label Quality Verification

Label inspection confirms label presence, correct position, registration accuracy, print quality, and barcode readability. Vision systems verify label location within tolerance bands, check for wrinkles or air bubbles affecting appearance, verify text legibility, and read barcodes confirming correct content and readability by downstream systems.

Advanced inspection includes optical character recognition (OCR) reading date codes and lot numbers printed or labeled on bottles, verifying correct information matches production batch parameters stored in recipe systems. Barcode verification ensures GS1 compliance for retail distribution enabling proper scanning throughout supply chains.

Chapter 2: PLC System Architecture for Bottling Lines

Distributed Control System Design

High-speed bottling lines use distributed control architectures dividing control responsibilities across multiple PLCs or controllers rather than centralizing all logic in single processors. This approach improves performance, enables parallel processing, simplifies programming, and provides fault isolation limiting single-point failures.

Centralized vs Distributed Architecture Comparison

Centralized systems use a single large PLC controlling all line equipment through extensive I/O networks. This approach simplifies program structure and data sharing but creates bottlenecks as all processing occurs in one controller. Scan time limitations restrict maximum line complexity and response speed.

Distributed architectures assign dedicated PLCs or controllers to major equipment modules (depalletizer, rinser, filler, capper, labeler, inspector, packer) with peer-to-peer communication coordinating operations. Each controller handles local I/O and machine-specific logic while sharing production status, bottle counts, and control commands through industrial Ethernet networks.

Hybrid architectures combine both approaches with a line coordinator PLC managing overall system control and recipe management while equipment module controllers handle local operations. The coordinator acts as the master receiving commands from SCADA systems, distributing setpoints to modules, collecting production data, and arbitrating line-wide sequences including startups, shutdowns, and mode transitions.

PLC Platform Selection for Beverage Applications

Bottling applications demand PLCs offering high I/O capacity, advanced motion control, robust industrial Ethernet communication, extensive memory for recipe storage, and food-grade certifications where equipment contacts product.

Siemens S7-1500 series provides comprehensive capabilities including PROFINET for distributed I/O and motion control, integrated safety functions through ET200SP safety modules, and TIA Portal programming environment supporting ladder logic, structured text, and function block programming. Typical installations use S7-1515 or S7-1517 CPUs with 1-3MB program memory handling complex bottling line logic.

Allen-Bradley ControlLogix platforms dominate North American beverage installations offering EtherNet/IP communication, integrated motion control through Kinetix servo drives, and extensive add-on instruction libraries accelerating development. L8 series controllers provide multi-core processors enabling deterministic motion control simultaneously with complex logic execution.

Omron NJ/NX series controllers excel in high-speed applications requiring many synchronized axes through EtherCAT communication achieving cycle times under 500μs. Sysmac Studio development environment provides unified programming for logic, motion, robotics, and vision simplifying complex bottling automation.

Beckhoff TwinCAT transforms industrial PCs into soft PLCs delivering extreme performance for demanding applications exceeding 100 servo axes. PC-based architecture provides flexibility and processing power unavailable from traditional PLC hardware but requires different reliability considerations including UPS systems and redundant component specifications.

Motion Control and Servo Integration

Understanding Bottling Motion Requirements

Bottling lines extensively use servo motors for applications requiring precision positioning, coordinated multi-axis motion, and high-speed synchronized operation. Typical servo applications include rotary filler main drive, infeed and discharge star wheels, label feed mechanisms, cap placement heads, and bottle handling transfers.

Electronic line shaft architecture creates virtual mechanical connections between all conveyors, star wheels, and rotary machines through electronic gearing and camming. A master position axis representing overall line position drives all physical axes through calculated gear ratios ensuring perfect synchronization regardless of speed variations. This approach eliminates mechanical line shafts, gearboxes, and timing belts while providing flexibility for quick product changeovers through recipe-based gear ratio adjustments.

Master axis programming uses either a virtual axis incremented in program logic based on line speed setpoint or a physical encoder mounted on a primary conveyor motor. Virtual masters offer flexibility for complex speed control algorithms while physical encoder masters provide guaranteed synchronization to actual mechanical motion beneficial for registration-critical applications.

Servo Drive Communication Networks

Modern bottling systems use deterministic industrial Ethernet protocols for servo communication enabling simultaneous control of many axes with precise timing guarantees. EtherCAT provides the highest performance with update cycles down to 100μs and sub-microsecond jitter supporting extremely demanding synchronization. PROFINET IRT (Isochronous Real-Time) offers similar performance integrated with Siemens ecosystems. EtherNet/IP using CIP Motion provides robust capabilities well-suited to Allen-Bradley platforms though with slightly longer cycle times (1-2ms typical).

Drive configuration includes motor pairing defining motor type, power rating, encoder resolution, and electrical parameters; position scaling establishing engineering units (mm, degrees, bottles) for position references; velocity and torque limits preventing mechanical damage from excessive speeds or forces; and homing procedures establishing known reference positions for absolute positioning applications.

Tuning servo systems optimizes dynamic response balancing speed and stability. Bottling applications often require aggressive tuning for rapid acceleration during startup and deceleration during stops while maintaining smooth motion during production preventing product spillage from filled bottles. Auto-tuning utilities provide starting points requiring refinement based on mechanical characteristics and load variations.

Industrial Ethernet Networks and I/O Distribution

PROFINET and EtherNet/IP Implementation

High-speed bottling lines distribute I/O close to sensing and actuation points using industrial Ethernet I/O modules rather than running thousands of wires back to central PLC cabinets. PROFINET and EtherNet/IP enable this distributed architecture through deterministic communication protocols supporting both standard I/O and motion control on shared network infrastructure.

Network topology design considers communication bandwidth, redundancy requirements, and physical equipment layout. Line topology connects devices in series suitable for equipment arranged linearly along production lines. Star topology centralizes network switches in control cabinets with individual connections to equipment modules providing redundancy through parallel paths. Ring topology creates closed loops with redundancy protocols automatically rerouting communication if cable breaks occur anywhere in the ring.

I/O module placement locates inputs and outputs near physical devices minimizing sensor cable runs, reducing electrical noise susceptibility, and simplifying troubleshooting. Typical bottling line installations use 8-16 distributed I/O stations positioned at major equipment modules. Each station provides 16-64 digital inputs, 8-32 digital outputs, and 4-8 analog channels sufficient for local equipment requirements.

Programming accesses distributed I/O identically to local I/O with network addresses distinguishing physical locations. Modern PLCs provide automatic configuration discovering networked devices and populating hardware trees in programming software. Diagnostic tags provide network health information including device status, communication errors, and bus performance metrics enabling proactive maintenance.

SCADA Integration and Data Collection

Supervisory Control and Data Acquisition (SCADA) systems provide operator interfaces, production monitoring, recipe management, and historical data collection for bottling operations. SCADA systems connect to PLCs through OPC UA, proprietary Ethernet protocols, or database gateways extracting real-time production data and sending control commands.

Integration architecture separates control networks (PLC-to-PLC and PLC-to-I/O communication) from information networks (SCADA, MES, and enterprise systems) through industrial switches or firewalls preventing IT network issues from affecting production control. PLCs expose data through OPC UA servers or native protocol gateways, with SCADA clients polling tag values at appropriate update rates balancing data currency against network loading.

Programming considerations include defining tag structures organizing related data for efficient SCADA polling, implementing handshaking protocols for recipe downloads and production commands ensuring data integrity, providing alarming systems with prioritization and acknowledgment tracking, and optimizing data collection for trending and reporting without impacting control system performance.

Chapter 3: Bottle Handling and Conveying Control

Air Conveyor Systems and Pressure Management

Air conveyor systems transport lightweight PET bottles on cushions of low-pressure air avoiding mechanical contact that could scratch surfaces or deform thin-walled containers. This technology dominates modern high-speed bottling for water, carbonated soft drinks, and other beverages packaged in PET containers weighing as little as 8-12 grams before filling.

Air Conveyor Operating Principles

Air conveyors use perforated conveyor decks or air bars with thousands of small holes through which compressed air flows creating an air cushion supporting bottles while allowing forward motion from mechanical drives or air flow itself. Bottle weight compresses the air cushion creating pressure buildup that supports bottles while air escaping around bottle bases provides lubrication enabling smooth sliding motion.

Pressure requirements depend on bottle weight, base design, and desired transport characteristics. Empty PET bottles typically require 0.1-0.3 bar (1.5-4.5 PSI) air pressure while filled bottles may need 0.2-0.5 bar. Excessive pressure causes unstable bottle behavior with jumping or tipping while insufficient pressure creates excessive friction preventing smooth transport and potentially causing bottle jams.

PLC programming manages air pressure regulation through proportional pressure control valves or pressure regulators with feedback from pressure transducers. Different line sections require independent pressure zones as empty bottles need different pressure than filled bottles, and straight sections require different pressure than curves or bottle accumulation areas.

Zone-Based Pressure Control Programming

Advanced air conveyor control divides lines into multiple pressure zones with independent regulation adapting to bottle conditions and operational requirements. Programming monitors bottle presence in each zone adjusting pressure based on occupancy levels and bottle characteristics.

// Air Conveyor Pressure Control
// Siemens S7-1500 SCL (Structured Control Language)

PROGRAM AirConveyorControl
VAR
    // Zone configuration (4 pressure zones example)
    Zone1_BottlePresent : BOOL;      // Zone 1 bottle sensor
    Zone2_BottlePresent : BOOL;
    Zone3_BottlePresent : BOOL;
    Zone4_BottlePresent : BOOL;

    Zone1_Pressure : REAL;           // Actual pressure (bar)
    Zone2_Pressure : REAL;
    Zone3_Pressure : REAL;
    Zone4_Pressure : REAL;

    Zone1_PressureSetpoint : REAL;   // Target pressure setpoints
    Zone2_PressureSetpoint : REAL;
    Zone3_PressureSetpoint : REAL;
    Zone4_PressureSetpoint : REAL;

    Zone1_PressureValve : REAL;      // Valve position outputs (0-100%)
    Zone2_PressureValve : REAL;
    Zone3_PressureValve : REAL;
    Zone4_PressureValve : REAL;

    // Recipe parameters
    EmptyBottlePressure : REAL := 0.15;     // Empty bottle pressure (bar)
    FilledBottlePressure : REAL := 0.35;    // Filled bottle pressure (bar)
    AccumulationPressure : REAL := 0.10;    // Reduced pressure for accumulation

    // Zone PID controllers
    Zone1_PID : PID_Compact;
    Zone2_PID : PID_Compact;
    Zone3_PID : PID_Compact;
    Zone4_PID : PID_Compact;

    // Line status
    LineRunning : BOOL;
    FillerDischargeActive : BOOL;    // Filled bottles entering Zone 2
    AccumulationMode : BOOL;         // Accumulation table active

END_VAR

// Zone 1 - Empty bottle infeed from depalletizer
IF LineRunning THEN
    Zone1_PressureSetpoint := EmptyBottlePressure;
ELSE
    Zone1_PressureSetpoint := 0.0;  // No pressure when stopped
END_IF;

// Zone 2 - Filled bottle discharge from filler
IF LineRunning AND FillerDischargeActive THEN
    Zone2_PressureSetpoint := FilledBottlePressure;
ELSIF LineRunning THEN
    Zone2_PressureSetpoint := EmptyBottlePressure;
ELSE
    Zone2_PressureSetpoint := 0.0;
END_IF;

// Zone 3 - Accumulation table with dynamic pressure
IF AccumulationMode THEN
    // Reduced pressure when bottles accumulating
    Zone3_PressureSetpoint := AccumulationPressure;
ELSIF LineRunning AND FillerDischargeActive THEN
    Zone3_PressureSetpoint := FilledBottlePressure;
ELSE
    Zone3_PressureSetpoint := EmptyBottlePressure;
END_IF;

// Zone 4 - Labeling area (always filled bottles)
IF LineRunning THEN
    Zone4_PressureSetpoint := FilledBottlePressure;
ELSE
    Zone4_PressureSetpoint := 0.0;
END_IF;

// PID pressure control for Zone 1
Zone1_PID.Setpoint := Zone1_PressureSetpoint;
Zone1_PID.Input := Zone1_Pressure;
Zone1_PID.ManualValue := 0.0;
Zone1_PID.Mode := TRUE;  // Automatic mode
Zone1_PID();
Zone1_PressureValve := Zone1_PID.Output;

// Repeat PID control for Zones 2-4
// (Similar structure for each zone)

// Fault detection - pressure deviation alarms
IF ABS(Zone1_Pressure - Zone1_PressureSetpoint) > 0.05 THEN
    // Zone 1 pressure fault - check air supply or valve
END_IF;

END_PROGRAM

This pressure control example demonstrates critical bottling automation concepts:

  • Recipe-based pressure setpoints adapt to different bottle types and filling states
  • Zone-independent control optimizes pressure for local conditions
  • PID closed-loop regulation maintains stable pressure despite flow variations
  • Accumulation mode reduces pressure enabling gentle bottle backup without tipping
  • Fault detection identifies air supply problems or control valve failures

Accumulation Table Control Logic

Accumulation tables provide buffering capacity between bottling line sections with different speeds or intermittent operations. Bottles collect on accumulation conveyors when downstream equipment runs slower than upstream supply, automatically releasing accumulated bottles when downstream capacity becomes available.

Back-Pressure Accumulation Systems

Back-pressure accumulation uses continuous conveyor belts with low-friction surfaces allowing bottles to slip against the moving belt when downstream blockage occurs. Bottles accumulate against each other with gentle contact pressure while the conveyor continues moving beneath them. When downstream flow resumes, bottles re-engage with the belt and advance forward.

Programming monitors accumulation table occupancy through multiple photoelectric sensors positioned along the table length. Low-level sensors near the discharge end trigger alarms if accumulation depletes risking downstream starvation. High-level sensors near the infeed end trigger upstream equipment slowdowns or stops preventing over-accumulation and bottle overflow.

Dynamic speed control adjusts upstream conveyor speeds based on accumulation levels. As accumulation builds indicating downstream slowdown, upstream speeds reduce maintaining consistent accumulation without abrupt stops. As accumulation clears indicating downstream capacity, upstream speeds increase restoring normal production flow.

Zero-Pressure Accumulation Control

Zero-pressure accumulation divides tables into multiple independently controlled zones with sensors detecting bottle presence in each zone. Zones operate only when bottles are present and the next zone has space available, preventing bottle-to-bottle contact and eliminating pressure buildup that could cause tipping or damage.

// Zero-Pressure Accumulation Table Control
// Allen-Bradley ControlLogix Structured Text

PROGRAM ZeroPressureAccumulation
VAR
    // 8-zone accumulation table
    Zone : ARRAY[1..8] OF AccumulationZone;

    OverallTableRunning : BOOL;
    DischargeRequest : BOOL;         // Downstream ready for bottles

    InfeedConveyor : BOOL;           // Infeed conveyor motor
    DischargeConveyor : BOOL;        // Discharge conveyor motor

END_VAR

TYPE AccumulationZone :
STRUCT
    PhotoEye : BOOL;                 // Zone occupancy sensor
    Motor : BOOL;                    // Zone motor control
    RunTimer : TON;                  // Minimum run time
    StopTimer : TON;                 // Delayed stop time
    NextZoneReady : BOOL;            // Next zone has capacity
END_STRUCT;
END_TYPE

VAR
    i : INT;
END_VAR

// Zone control logic
FOR i := 1 TO 8 DO
    // Determine if next zone is ready
    IF i = 8 THEN
        // Last zone - ready if discharge is requesting
        Zone[i].NextZoneReady := DischargeRequest;
    ELSE
        // Ready if next zone has space (not occupied)
        Zone[i].NextZoneReady := NOT Zone[i+1].PhotoEye;
    END_IF;

    // Zone motor control
    // Run if: table running AND bottles present AND next zone ready
    IF OverallTableRunning AND Zone[i].PhotoEye AND Zone[i].NextZoneReady THEN
        Zone[i].Motor := TRUE;
    ELSE
        // Add small delay before stopping to prevent chatter
        Zone[i].StopTimer(IN := NOT Zone[i].PhotoEye,
                         PT := T#500ms);

        IF Zone[i].StopTimer.Q THEN
            Zone[i].Motor := FALSE;
        END_IF;
    END_IF;

END_FOR;

// Infeed control - run if Zone 1 has space
IF OverallTableRunning THEN
    InfeedConveyor := NOT Zone[1].PhotoEye;
ELSE
    InfeedConveyor := FALSE;
END_IF;

// Discharge control - run when requested and bottles available
DischargeConveyor := OverallTableRunning AND DischargeRequest AND Zone[8].PhotoEye;

END_PROGRAM

Zero-pressure accumulation prevents bottle damage, reduces noise from bottle-to-bottle contact, and accommodates fragile containers unable to withstand back-pressure systems. This approach requires more sensors and control complexity but provides gentler handling critical for premium beverage packaging.

Star Wheel Timing and Bottle Spacing

Star wheels transfer bottles between linear conveyors and rotary equipment (fillers, cappers, labelers) or between conveyor sections requiring different speeds or orientations. Precise timing and electronic synchronization ensure smooth transfers without bottle collisions, gaps, or mechanical stress.

Star Wheel Geometry and Gear Ratio Calculations

Star wheel transfer efficiency depends on proper matching between linear conveyor speed, star wheel rotational speed, and downstream equipment speed. Gear ratio calculations establish the relationship between master line speed and individual star wheel speeds.

For a star wheel with N pockets (bottle-holding positions):

Star Wheel RPM = (Conveyor Speed × 60) / (N × Bottle Spacing)

Where conveyor speed is in mm/min, bottle spacing in mm, and N is the number of pockets.

Electronic gearing synchronizes star wheel servo drives to master line position ensuring each pocket arrives at the transfer point precisely as a bottle reaches that position. Programming calculates gear ratios from mechanical specifications and recipe parameters:

// Star Wheel Electronic Gearing
// Omron NJ-Series Structured Text

PROGRAM StarWheelControl
VAR
    // Axes
    MasterAxis : AXIS_REF;           // Line master position
    StarWheelAxis : AXIS_REF;        // Star wheel servo

    // Star wheel geometry
    StarWheelPockets : INT := 12;    // Number of bottle pockets
    PocketAngle : REAL;              // Degrees between pockets
    StarWheelDiameter : REAL := 600.0;  // Pitch diameter (mm)
    StarWheelCircumference : REAL;

    // Bottle spacing
    BottleSpacing : REAL := 157.0;   // Conveyor bottle spacing (mm)

    // Calculated gear ratio
    GearRatioNum : DINT;
    GearRatioDen : DINT;

    // Motion function blocks
    GearIn : MC_GearIn;
    GearOut : MC_GearOut;

    // Status
    StarWheelEnabled : BOOL;
    InGear : BOOL;

END_VAR

// Calculate star wheel geometry
PocketAngle := 360.0 / DINT_TO_REAL(StarWheelPockets);
StarWheelCircumference := 3.14159 * StarWheelDiameter;

// Calculate electronic gear ratio
// For each bottle spacing on conveyor, star wheel advances one pocket
// Master axis in mm, star wheel axis in degrees
// Ratio = (degrees per pocket) / (mm per bottle)

GearRatioNum := REAL_TO_DINT(PocketAngle * 1000.0);
GearRatioDen := REAL_TO_DINT(BottleSpacing * 1000.0);

// Engage electronic gearing
IF StarWheelEnabled THEN
    GearIn.Master := MasterAxis;
    GearIn.Slave := StarWheelAxis;
    GearIn.RatioNumerator := GearRatioNum;
    GearIn.RatioDenominator := GearRatioDen;
    GearIn.Acceleration := 5000.0;       // deg/s²
    GearIn.Deceleration := 5000.0;
    GearIn.Jerk := 50000.0;
    GearIn.Execute := TRUE;

    IF GearIn.InGear THEN
        GearIn.Execute := FALSE;
        InGear := TRUE;
    END_IF;

ELSE
    // Disengage gearing
    GearOut.Slave := StarWheelAxis;
    GearOut.Execute := TRUE;

    IF GearOut.Done THEN
        GearOut.Execute := FALSE;
        InGear := FALSE;
    END_IF;
END_IF;

// Call motion function blocks
GearIn();
GearOut();

END_PROGRAM

Proper star wheel synchronization requires accurate mechanical measurements including precise bottle spacing, exact star wheel pitch diameter, and confirmed pocket count. Small errors in these parameters cause accumulated position errors over time resulting in transfer failures and bottle jams.

Chapter 4: Rotary Filling Machine Programming

Electronic Filling Head Synchronization

Rotary filling machines use multiple filling heads (typically 6, 12, 18, 24, 36, 48, 72, or more) mounted on rotating carousels. Each filling head must execute identical filling sequences synchronized with carousel rotation ensuring consistent fill timing regardless of rotation speed or product changeovers.

Multi-Head Filling Coordination

Electronic camming coordinates complex filling sequences with carousel rotation. As the carousel rotates, each filling head follows programmed cam profiles executing nozzle lowering, valve opening, filling duration, valve closing, and nozzle raising at precise angular positions.

Cam profile design includes several critical phases:

  • Approach phase (0-10% of cycle): Bottle enters filling position, centering guides engage
  • Lower phase (10-20%): Filling nozzle descends into bottle opening
  • Fill phase (20-70%): Fill valve opens, product flows into bottle
  • Close phase (70-75%): Fill valve closes, residual product drains
  • Lift phase (75-85%): Nozzle retracts from bottle
  • Discharge phase (85-100%): Centering guides release, bottle exits position

Programming creates cam tables defining nozzle vertical position and valve state as functions of carousel angular position. Modern PLCs provide graphical cam editors enabling visual profile development with automatic velocity and acceleration limiting preventing mechanical shock.

// Rotary Filler Electronic Cam Control
// Beckhoff TwinCAT Structured Text

PROGRAM RotaryFillerControl
VAR
    // Axes
    CarouselAxis : AXIS_REF;         // Main carousel rotation
    NozzleAxes : ARRAY[1..12] OF AXIS_REF;  // 12 nozzle vertical axes

    // Cam control
    NozzleCams : ARRAY[1..12] OF MC_CamIn;
    CamTableID : DINT := 100;        // Nozzle cam profile table

    // Fill valves (pneumatic)
    FillValves : ARRAY[1..12] OF BOOL;

    // Fill control
    FillStartAngle : REAL := 72.0;   // Start fill at 72° into cycle
    FillEndAngle : REAL := 252.0;    // End fill at 252° (180° fill time)

    // Bottle detection at each head
    BottlePresent : ARRAY[1..12] OF BOOL;

    // Status
    FillerRunning : BOOL;
    CarouselAngle : REAL;            // Current carousel angle (0-360°)
    HeadAngle : ARRAY[1..12] OF REAL;  // Individual head angles

    i : INT;

END_VAR

// Calculate individual head angles
// Head 1 at reference position (0°)
// Heads evenly spaced: 360° / 12 heads = 30° spacing
FOR i := 1 TO 12 DO
    HeadAngle[i] := CarouselAngle + (DINT_TO_REAL(i-1) * 30.0);

    // Normalize to 0-360 range
    IF HeadAngle[i] >= 360.0 THEN
        HeadAngle[i] := HeadAngle[i] - 360.0;
    END_IF;

    // Engage cam control for nozzle positioning
    IF FillerRunning THEN
        NozzleCams[i].Master := CarouselAxis;
        NozzleCams[i].Slave := NozzleAxes[i];
        NozzleCams[i].CamTableID := CamTableID;
        NozzleCams[i].MasterOffset := 0.0;
        NozzleCams[i].SlaveOffset := 0.0;
        NozzleCams[i].Execute := TRUE;
    END_IF;

    // Fill valve control based on head angle and bottle presence
    IF FillerRunning AND BottlePresent[i] THEN
        IF (HeadAngle[i] >= FillStartAngle) AND
           (HeadAngle[i] <= FillEndAngle) THEN
            FillValves[i] := TRUE;
        ELSE
            FillValves[i] := FALSE;
        END_IF;
    ELSE
        FillValves[i] := FALSE;  // No fill if no bottle present
    END_IF;

    // Call cam function block
    NozzleCams[i]();

END_FOR;

// Carousel angle from axis position (assuming degrees)
CarouselAngle := CarouselAxis.ActualPosition;

// Normalize carousel angle to 0-360
WHILE CarouselAngle >= 360.0 DO
    CarouselAngle := CarouselAngle - 360.0;
END_WHILE;

WHILE CarouselAngle < 0.0 DO
    CarouselAngle := CarouselAngle + 360.0;
END_WHILE;

END_PROGRAM

This electronic cam approach provides several advantages over mechanical cam-driven fillers including programmable profiles adapting to different products without mechanical changes, synchronized operation across all heads eliminating individual cam manufacturing tolerances, and easy recipe management storing different cam profiles for various bottle sizes and products.

Electronic Filling Valve Control Algorithms

Electronic filling valves use precise actuation timing controlling product flow into bottles. Filling algorithms range from simple time-based control through sophisticated mass or volume feedback systems depending on accuracy requirements and product characteristics.

Time-Based Electronic Filling

Time-based filling opens electronically actuated valves for calibrated durations calculated to deliver target volumes based on product flow characteristics, supply pressure, and valve sizing. This approach suits applications where product consistency and stable process conditions enable reliable time-to-volume correlation.

Programming compensates for variables affecting fill accuracy including product temperature influencing viscosity and flow rate, supply pressure variations from tank level changes or pump performance, and valve response time variations from wear or contamination buildup. Temperature and pressure sensors provide real-time correction factors adjusting fill times maintaining volume consistency.

// Electronic Fill Valve Time-Based Control
// With Temperature and Pressure Compensation

PROGRAM ElectronicFillControl
VAR_INPUT
    FillTrigger : BOOL;              // Start fill command
    BottlePresent : BOOL;            // Bottle at fill position
    ProductTemp : REAL;              // Product temperature (°C)
    SupplyPressure : REAL;           // Fill pressure (bar)
END_VAR

VAR_OUTPUT
    FillValve : BOOL;                // Electronic valve control
    FillComplete : BOOL;             // Fill cycle complete
    ActualFillTime : TIME;           // Measured fill duration
END_VAR

VAR
    // Recipe parameters
    BaselineFillTime : TIME := T#1800ms;     // Baseline at 20°C, 2.0 bar
    TargetVolume : REAL := 500.0;            // Target volume (ml)

    ReferenceTemp : REAL := 20.0;            // Reference temperature
    ReferencePressure : REAL := 2.0;         // Reference pressure

    TempCoefficient : REAL := 0.015;         // 1.5% time change per °C
    PressureCoefficient : REAL := 0.25;      // 25% time change per bar

    // Calculated fill time
    CompensatedTime : TIME;
    TempFactor : REAL;
    PressureFactor : REAL;

    // Fill control
    State : INT := 0;
    FillTimer : TON;
    DrainTimer : TON;

END_VAR

// Calculate temperature compensation factor
// Higher temperature = lower viscosity = faster flow = shorter time
TempFactor := 1.0 - (TempCoefficient * (ProductTemp - ReferenceTemp));

// Calculate pressure compensation factor
// Higher pressure = faster flow = shorter time
PressureFactor := SQRT(ReferencePressure / SupplyPressure);

// Calculate compensated fill time
CompensatedTime := TIME_TO_DINT(BaselineFillTime) * TempFactor * PressureFactor;

// Fill state machine
CASE State OF
    0:  // Idle - waiting for fill trigger
        FillValve := FALSE;
        FillComplete := FALSE;

        IF FillTrigger AND BottlePresent THEN
            State := 10;
        END_IF;

    10: // Open valve and fill
        FillValve := TRUE;

        FillTimer(IN := TRUE,
                 PT := CompensatedTime,
                 Q => ,
                 ET => ActualFillTime);

        IF FillTimer.Q THEN
            FillTimer(IN := FALSE);
            FillValve := FALSE;
            State := 20;
        END_IF;

    20: // Drain delay preventing drips
        DrainTimer(IN := TRUE,
                  PT := T#300ms,
                  Q => ,
                  ET => );

        IF DrainTimer.Q THEN
            DrainTimer(IN := FALSE);
            FillComplete := TRUE;
            State := 0;
        END_IF;

END_CASE;

END_PROGRAM

Mass Flow Meter Integration

Advanced filling systems use mass flow meters or Coriolis meters providing real-time measurement of dispensed product mass. These systems achieve exceptional accuracy (±0.1% or better) independent of product temperature, density, or viscosity variations.

Integration requires high-speed analog input modules or digital communication interfaces (PROFINET, EtherNet/IP, IO-Link) reading instantaneous flow rates and totalizing dispensed mass. Closed-loop control compares accumulated mass against target values, closing fill valves when targets are reached with predictive shutoff compensating for valve response delay and fill-in-flight.

// Mass Flow Meter Filling Control
// Siemens S7-1500 with PROFINET Flow Meter

PROGRAM MassFlowFilling
VAR
    // Flow meter interface (PROFINET)
    FlowMeter_TotalMass : REAL;      // Accumulated mass (grams)
    FlowMeter_FlowRate : REAL;       // Instantaneous flow (g/s)
    FlowMeter_Reset : BOOL;          // Reset totalizer

    // Fill control
    FillValve : BOOL;
    FastFillValve : BOOL;            // High-flow valve
    SlowFillValve : BOOL;            // Precision valve

    // Recipe parameters
    TargetMass : REAL := 500.0;      // Target fill mass (grams)
    Tolerance : REAL := 0.5;         // Acceptable tolerance (±grams)
    FastFillCutoff : REAL := 0.92;   // Fast fill to 92% of target
    SlowFillCutoff : REAL := 0.98;   // Slow fill to 98% of target

    // Predictive shutoff
    ValveDelay : TIME := T#80ms;     // Valve closing delay
    FillInFlight : REAL;             // Calculated in-flight mass
    PredictedFinal : REAL;           // Predicted final mass

    // State machine
    State : INT := 0;
    FillTrigger : BOOL;
    FillComplete : BOOL;
    FinalMass : REAL;

END_VAR

// Calculate fill-in-flight prediction
// Mass that will flow during valve closing delay
FillInFlight := FlowMeter_FlowRate * (TIME_TO_REAL(ValveDelay) / 1000.0);
PredictedFinal := FlowMeter_TotalMass + FillInFlight;

// Multi-stage filling control
CASE State OF
    0:  // Idle
        FastFillValve := FALSE;
        SlowFillValve := FALSE;
        FillComplete := FALSE;

        IF FillTrigger THEN
            FlowMeter_Reset := TRUE;
            State := 10;
        END_IF;
        FlowMeter_Reset := FALSE;

    10: // Fast fill stage
        FastFillValve := TRUE;

        // Advance when predicted mass reaches fast fill cutoff
        IF PredictedFinal >= (TargetMass * FastFillCutoff) THEN
            FastFillValve := FALSE;
            State := 20;
        END_IF;

    20: // Slow fill stage for precision
        SlowFillValve := TRUE;

        // Close when predicted mass reaches slow fill cutoff
        IF PredictedFinal >= (TargetMass * SlowFillCutoff) THEN
            SlowFillValve := FALSE;
            State := 30;
        END_IF;

    30: // Dribble fill to exact target
        // Very slow valve or pulsed control for final accuracy
        IF FlowMeter_FlowRate < 1.0 THEN  // Flow nearly stopped
            FinalMass := FlowMeter_TotalMass;

            IF ABS(FinalMass - TargetMass) <= Tolerance THEN
                FillComplete := TRUE;
                State := 0;
            ELSIF FinalMass < TargetMass THEN
                // Need slight additional fill
                SlowFillValve := TRUE;
            ELSE
                // Overfilled - cannot correct
                FillComplete := TRUE;
                State := 0;
            END_IF;
        END_IF;

END_CASE;

END_PROGRAM

Mass flow meter systems provide the highest accuracy for premium products, pharmaceutical beverages, and applications where product value justifies instrumentation investment. These systems automatically adapt to product variations without recalibration making them ideal for facilities producing multiple beverage types.

Chapter 5: Capping and Labeling Automation

Automated Capping Sequence Control

Capping systems apply closures and tighten them to specified torque ensuring proper sealing without over-tightening causing damage or under-tightening risking leakage. Rotary capping machines handle high speeds through continuous motion while maintaining precise torque control across all capping heads.

Cap Placement and Torque Application

Modern capping systems use servo-driven spinning heads applying closures through programmable torque profiles. Torque control methods include direct torque sensing through servo drive current measurement, indirect torque calculation from servo drive parameters, or dedicated torque transducers providing highest accuracy.

Programming implements torque ramp profiles gradually increasing torque preventing sudden loads that could cause bottle rotation or cap damage. Typical profiles start at low torque (20-30% of target) for initial thread engagement, ramp to target torque over specified time or rotation angle, maintain target torque verifying proper engagement, then release allowing bottle discharge.

// Servo Capping Head Torque Control
// Allen-Bradley ControlLogix with Kinetix Servo

PROGRAM ServoCappingControl
VAR
    // Servo axis
    CappingAxis : AXIS_REF;

    // Motion control
    MoveVelocity : MC_MoveVelocity;
    TorqueLimitControl : MC_TorqueControl;

    // Cap application sensors
    BottlePresent : BOOL;
    CapPresent : BOOL;
    CapPlaced : BOOL;

    // Recipe parameters
    TargetTorque : REAL := 15.0;     // Target torque (in-lbs)
    TorqueTolerance : REAL := 1.5;   // Acceptable range (±in-lbs)
    CapSpeed : REAL := 600.0;        // Capping speed (RPM)
    ApproachSpeed : REAL := 100.0;   // Initial engagement speed

    // Torque profile
    InitialTorque : REAL := 5.0;     // Light engagement torque
    RampTime : TIME := T#500ms;      // Torque ramp duration

    // Measured values
    ActualTorque : REAL;             // From servo drive
    ActualAngle : REAL;              // Cap rotation angle

    // State machine
    State : INT := 0;
    CappingTrigger : BOOL;
    CappingComplete : BOOL;
    TorqueOK : BOOL;

    // Timers
    RampTimer : TON;
    DwellTimer : TON;

END_VAR

// Capping sequence state machine
CASE State OF
    0:  // Idle - waiting for bottle and cap
        CappingComplete := FALSE;

        IF CappingTrigger AND BottlePresent AND CapPresent THEN
            State := 10;
        END_IF;

    10: // Lower capping head and place cap
        // Vertical positioning would be handled by separate axis
        // Programming omitted for brevity

        IF CapPlaced THEN
            ActualAngle := 0.0;
            State := 20;
        END_IF;

    20: // Initial engagement at low speed and torque
        MoveVelocity.Axis := CappingAxis;
        MoveVelocity.Velocity := ApproachSpeed;
        MoveVelocity.Acceleration := 1000.0;
        MoveVelocity.Deceleration := 1000.0;
        MoveVelocity.Jerk := 5000.0;
        MoveVelocity.Execute := TRUE;

        TorqueLimitControl.Axis := CappingAxis;
        TorqueLimitControl.TorqueLimit := InitialTorque;
        TorqueLimitControl.Execute := TRUE;

        // Wait for initial thread engagement
        IF ActualAngle >= 90.0 THEN  // 1/4 turn engagement
            State := 30;
        END_IF;

    30: // Ramp to full speed and target torque
        MoveVelocity.Velocity := CapSpeed;

        RampTimer(IN := TRUE,
                 PT := RampTime,
                 Q => ,
                 ET => );

        // Linearly ramp torque limit to target
        TorqueLimitControl.TorqueLimit := InitialTorque +
            ((TargetTorque - InitialTorque) *
             (TIME_TO_REAL(RampTimer.ET) / TIME_TO_REAL(RampTime)));

        IF RampTimer.Q THEN
            RampTimer(IN := FALSE);
            State := 40;
        END_IF;

    40: // Dwell at target torque
        TorqueLimitControl.TorqueLimit := TargetTorque;

        DwellTimer(IN := TRUE,
                  PT := T#200ms,
                  Q => ,
                  ET => );

        IF DwellTimer.Q THEN
            DwellTimer(IN := FALSE);
            ActualTorque := CappingAxis.ActualTorque;  // Read final torque
            State := 50;
        END_IF;

    50: // Stop rotation and verify torque
        MoveVelocity.Execute := FALSE;
        TorqueLimitControl.Execute := FALSE;

        // Verify torque within acceptable range
        TorqueOK := (ABS(ActualTorque - TargetTorque) <= TorqueTolerance);

        CappingComplete := TRUE;
        State := 60;

    60: // Raise capping head and release bottle
        // Vertical retraction
        // Discharge bottle

        State := 0;  // Return to idle

END_CASE;

// Call motion function blocks
MoveVelocity();
TorqueLimitControl();

END_PROGRAM

Torque verification ensures cap application quality with statistical data collection tracking torque values for process control charting. Trend analysis identifies gradual changes indicating wearing equipment or improper cap supply requiring maintenance or adjustments.

High-Speed Label Application

Label applicators use electronic synchronization coordinating label feed with bottle conveyors ensuring accurate placement at production speeds exceeding 600 bottles per minute. Servo-driven systems provide flexibility and precision unattainable with mechanical cam-driven applicators.

Label Registration and Position Control

Registration control maintains label placement accuracy by detecting printed marks or label edges and correcting position errors. High-speed applications use encoder tracking and mark sensors generating position error signals feeding into registration control algorithms.

Mark detection triggers high-speed counter snapshots capturing encoder position when marks are detected. Comparison with expected position based on label length and previous marks generates position error. Registration controllers adjust label feed speed or position offset compensating for accumulated error over multiple labels.

// Label Registration Control
// Omron NJ-Series with Electronic Gearing

PROGRAM LabelRegistrationControl
VAR
    // Axes
    ConveyorAxis : AXIS_REF;         // Master conveyor position
    LabelFeedAxis : AXIS_REF;        // Label feed servo

    // Registration inputs
    LabelMarkSensor : BOOL;          // Mark detection sensor
    LabelMarkPosition : DINT;        // Encoder count at mark detect

    // Label specifications
    LabelLength : REAL := 120.0;     // Label length (mm)
    LabelGap : REAL := 3.0;          // Gap between labels (mm)
    PrintMarkPosition : REAL := 115.0;  // Mark position from label leading edge

    // Bottle spacing
    BottleSpacing : REAL := 160.0;   // Bottle pitch on conveyor (mm)

    // Electronic gearing
    GearIn : MC_GearIn;
    NominalGearRatio : REAL;
    ActiveGearRatio : REAL;

    // Registration error correction
    ExpectedMarkPosition : DINT;
    PositionError : REAL;            // Error in mm
    ErrorCorrection : REAL;          // Gear ratio adjustment
    CorrectionGain : REAL := 0.15;   // Correction strength (15%)

    // Counters and tracking
    LabelCount : DINT := 0;
    LastMarkPosition : DINT;
    MarkDetected : BOOL;
    MarkDetectedOld : BOOL;

    // Status
    RegistrationActive : BOOL;
    RegistrationError : REAL;        // Current error for HMI display

END_VAR

// Calculate nominal gear ratio
// For each bottle spacing, advance one label + gap
NominalGearRatio := (LabelLength + LabelGap) / BottleSpacing;

// Detect registration mark rising edge
MarkDetected := LabelMarkSensor AND NOT MarkDetectedOld;
MarkDetectedOld := LabelMarkSensor;

IF MarkDetected THEN
    // New mark detected - calculate position error
    LabelCount := LabelCount + 1;

    // Expected position for this mark
    // First mark establishes reference
    IF LabelCount = 1 THEN
        ExpectedMarkPosition := LabelMarkPosition;
        LastMarkPosition := LabelMarkPosition;
        PositionError := 0.0;
    ELSE
        // Subsequent marks should be spaced by (LabelLength + LabelGap)
        ExpectedMarkPosition := LastMarkPosition +
                               REAL_TO_DINT(LabelLength + LabelGap);

        // Calculate actual position error (in encoder counts)
        PositionError := DINT_TO_REAL(LabelMarkPosition - ExpectedMarkPosition);

        // Convert to mm (assuming encoder resolution known)
        // Example: 100 counts per mm
        RegistrationError := PositionError / 100.0;

        LastMarkPosition := LabelMarkPosition;
    END_IF;

    // Calculate corrective gear ratio adjustment
    // Positive error (mark detected late) → increase speed
    // Negative error (mark detected early) → decrease speed
    ErrorCorrection := CorrectionGain * (PositionError / 100.0) / BottleSpacing;

    // Apply correction to gear ratio
    ActiveGearRatio := NominalGearRatio * (1.0 + ErrorCorrection);

    // Limit correction range preventing excessive adjustments
    IF ActiveGearRatio > (NominalGearRatio * 1.10) THEN
        ActiveGearRatio := NominalGearRatio * 1.10;  // Max +10%
    ELSIF ActiveGearRatio < (NominalGearRatio * 0.90) THEN
        ActiveGearRatio := NominalGearRatio * 0.90;  // Max -10%
    END_IF;

ELSE
    // Use current active ratio
    // (Gear ratio remains from last correction)
END_IF;

// Engage electronic gearing with corrected ratio
IF RegistrationActive THEN
    GearIn.Master := ConveyorAxis;
    GearIn.Slave := LabelFeedAxis;
    GearIn.RatioNumerator := REAL_TO_DINT(ActiveGearRatio * 10000.0);
    GearIn.RatioDenominator := 10000;
    GearIn.Execute := TRUE;

    IF GearIn.InGear AND GearIn.Execute THEN
        GearIn.Execute := FALSE;
    END_IF;
END_IF;

// Call motion function block
GearIn();

// Fault detection - excessive registration error
IF ABS(RegistrationError) > 5.0 THEN
    // Registration error exceeds 5mm - alarm condition
    // May indicate label web splice, material problem, or sensor fault
END_IF;

END_PROGRAM

Registration control automatically compensates for label material variations, splice locations where labels may shift, and mechanical tolerances in label feed mechanisms. This closed-loop approach maintains placement accuracy typically within ±1mm despite these disturbances.

Chapter 6: Vision Inspection and Quality Control

Integrated Vision System Programming

Vision inspection systems verify product quality at line speeds through automated image analysis detecting fill levels, cap presence and orientation, label placement, date code verification, and package defects. PLC integration coordinates triggering, receives results, and manages reject diversion.

Vision System Communication Architecture

Vision systems communicate with PLCs through multiple protocols depending on complexity and data requirements. Simple discrete I/O suffices for basic pass/fail inspection using vision processor discrete outputs signaling results to PLC inputs. This approach handles fill level checking, cap presence verification, and simple label inspection.

Industrial Ethernet protocols (EtherNet/IP, PROFINET, Ethernet TCP/IP) enable comprehensive communication for complex applications. PLCs trigger inspections synchronized with product position, receive detailed measurement data and defect classifications, send product recipe information configuring inspection parameters, and access diagnostic information for system health monitoring.

// Vision System Integration with EtherNet/IP
// Allen-Bradley ControlLogix with Cognex Vision

PROGRAM VisionInspectionControl
VAR
    // Vision system communication (EtherNet/IP tags)
    Vision_TriggerInspection : BOOL;       // Trigger image capture
    Vision_InspectionComplete : BOOL;      // Result ready
    Vision_OverallPass : BOOL;             // Combined pass/fail
    Vision_FillLevelPass : BOOL;           // Fill level OK
    Vision_CapPresent : BOOL;              // Cap detected
    Vision_LabelPass : BOOL;               // Label placement OK
    Vision_BarcodeReadable : BOOL;         // Barcode scan success

    Vision_FillLevel : REAL;               // Measured fill level (mm)
    Vision_LabelOffset : REAL;             // Label offset from center (mm)
    Vision_BarcodeData : STRING[20];       // Decoded barcode

    Vision_RecipeNumber : INT;             // Active recipe selection
    Vision_SystemStatus : INT;             // Health status

    // Product tracking
    ProductQueue : ARRAY[1..50] OF ProductData;
    QueueIndex : INT := 1;
    RejectIndex : INT := 1;

    // Sensors and timing
    TriggerSensor : BOOL;                  // Inspection position sensor
    RejectGateSensor : BOOL;               // Reject diversion sensor

    TriggerToReject : TIME := T#2500ms;    // Transit time to reject gate
    RejectTimer : TON;

    // Outputs
    RejectDiverter : BOOL;                 // Reject gate solenoid

    // Statistics
    BottlesInspected : DINT := 0;
    BottlesRejected : DINT := 0;
    RejectByFillLevel : DINT := 0;
    RejectByCap : DINT := 0;
    RejectByLabel : DINT := 0;

    // Trigger detection
    TriggerDetected : BOOL;
    TriggerOld : BOOL;

END_VAR

TYPE ProductData :
STRUCT
    InspectionPass : BOOL;
    RejectReason : INT;              // 0=OK, 1=Fill, 2=Cap, 3=Label, 4=Barcode
    FillLevel : REAL;
    BarcodeData : STRING[20];
END_STRUCT;
END_TYPE;

// Detect inspection trigger rising edge
TriggerDetected := TriggerSensor AND NOT TriggerOld;
TriggerOld := TriggerSensor;

// Trigger vision inspection
IF TriggerDetected THEN
    Vision_TriggerInspection := TRUE;
    BottlesInspected := BottlesInspected + 1;
END_IF;

// Reset trigger after vision acknowledges
IF Vision_InspectionComplete THEN
    Vision_TriggerInspection := FALSE;
END_IF;

// Process vision results when available
IF Vision_InspectionComplete AND NOT TriggerDetected THEN
    // Store results in tracking queue
    ProductQueue[QueueIndex].InspectionPass := Vision_OverallPass;
    ProductQueue[QueueIndex].FillLevel := Vision_FillLevel;
    ProductQueue[QueueIndex].BarcodeData := Vision_BarcodeData;

    // Determine reject reason if failed
    IF NOT Vision_OverallPass THEN
        IF NOT Vision_FillLevelPass THEN
            ProductQueue[QueueIndex].RejectReason := 1;
            RejectByFillLevel := RejectByFillLevel + 1;
        ELSIF NOT Vision_CapPresent THEN
            ProductQueue[QueueIndex].RejectReason := 2;
            RejectByCap := RejectByCap + 1;
        ELSIF NOT Vision_LabelPass THEN
            ProductQueue[QueueIndex].RejectReason := 3;
            RejectByLabel := RejectByLabel + 1;
        ELSIF NOT Vision_BarcodeReadable THEN
            ProductQueue[QueueIndex].RejectReason := 4;
        END_IF;

        BottlesRejected := BottlesRejected + 1;
    ELSE
        ProductQueue[QueueIndex].RejectReason := 0;
    END_IF;

    // Advance queue index
    QueueIndex := QueueIndex + 1;
    IF QueueIndex > 50 THEN
        QueueIndex := 1;
    END_IF;
END_IF;

// Reject diverter control
// Products reach reject gate after fixed transit time
RejectTimer(IN := TriggerDetected,
           PT := TriggerToReject,
           Q => ,
           ET => );

IF RejectTimer.Q THEN
    // Check if product at reject gate should be diverted
    RejectDiverter := NOT ProductQueue[RejectIndex].InspectionPass;

    // Advance reject index
    RejectIndex := RejectIndex + 1;
    IF RejectIndex > 50 THEN
        RejectIndex := 1;
    END_IF;

    RejectTimer(IN := FALSE);
END_IF;

// Diverter deactivation after actuation time
// (Additional timer logic for diverter timing)

END_PROGRAM

Product tracking through inspection and reject zones requires careful timing coordination. Encoder-based position tracking provides superior accuracy over time-based methods, especially during line speed changes or brief stops that would corrupt time-based calculations.

Statistical Process Control Integration

Quality data collection enables statistical process control (SPC) identifying process trends before systematic defects develop. Programming calculates real-time statistics including mean, standard deviation, and control limits for critical parameters like fill level, cap torque, and label placement.

// Fill Level SPC Tracking
// Moving average and standard deviation calculation

PROGRAM FillLevelSPC
VAR
    // Data collection
    FillLevelSamples : ARRAY[1..100] OF REAL;
    SampleIndex : INT := 1;
    SampleCount : INT := 0;

    // Statistical calculations
    SampleSum : REAL := 0.0;
    SampleSumSquares : REAL := 0.0;
    Mean : REAL;
    StdDev : REAL;
    Variance : REAL;

    // Control limits (±3 sigma)
    UpperControlLimit : REAL;
    LowerControlLimit : REAL;

    // Target specifications
    TargetFillLevel : REAL := 190.0;  // Target 190mm from bottle base
    Specification : REAL := 3.0;      // Spec tolerance ±3mm

    // Process capability
    ProcessCapability : REAL;         // Cp index

    // Alarms
    ProcessOutOfControl : BOOL;
    ProcessDrift : BOOL;

    i : INT;

END_VAR

// Add new sample to array
IF Vision_InspectionComplete THEN
    FillLevelSamples[SampleIndex] := Vision_FillLevel;

    SampleIndex := SampleIndex + 1;
    IF SampleIndex > 100 THEN
        SampleIndex := 1;
    END_IF;

    IF SampleCount < 100 THEN
        SampleCount := SampleCount + 1;
    END_IF;
END_IF;

// Calculate statistics on full dataset
IF SampleCount >= 30 THEN  // Minimum samples for valid statistics
    SampleSum := 0.0;
    SampleSumSquares := 0.0;

    FOR i := 1 TO SampleCount DO
        SampleSum := SampleSum + FillLevelSamples[i];
        SampleSumSquares := SampleSumSquares +
                           (FillLevelSamples[i] * FillLevelSamples[i]);
    END_FOR;

    // Calculate mean
    Mean := SampleSum / DINT_TO_REAL(SampleCount);

    // Calculate variance and standard deviation
    Variance := (SampleSumSquares / DINT_TO_REAL(SampleCount)) - (Mean * Mean);
    StdDev := SQRT(Variance);

    // Calculate control limits (±3 sigma)
    UpperControlLimit := Mean + (3.0 * StdDev);
    LowerControlLimit := Mean - (3.0 * StdDev);

    // Calculate process capability (Cp)
    // Cp = (Spec Range) / (6 * StdDev)
    ProcessCapability := (2.0 * Specification) / (6.0 * StdDev);

    // Detect out-of-control condition
    // Mean shifted from target by more than 1.5mm
    IF ABS(Mean - TargetFillLevel) > 1.5 THEN
        ProcessDrift := TRUE;
    ELSE
        ProcessDrift := FALSE;
    END_IF;

    // Detect excessive variation
    // Process capability below minimum acceptable
    IF ProcessCapability < 1.33 THEN
        ProcessOutOfControl := TRUE;
    ELSE
        ProcessOutOfControl := FALSE;
    END_IF;

END_IF;

END_PROGRAM

SPC trending enables predictive maintenance and process optimization. Gradual fill level increases may indicate worn filling valves requiring service, while increasing variation suggests mechanical problems with bottle positioning or filling nozzle alignment.

Chapter 7: Clean-in-Place (CIP) Automation

CIP System Architecture and Control

Clean-in-Place (CIP) systems automate cleaning and sanitization of product-contact surfaces without equipment disassembly. Beverage bottling CIP encompasses filling equipment, product piping, storage tanks, and sometimes rinsing equipment requiring periodic sanitation maintaining microbiological safety.

CIP Sequence Programming

CIP cycles execute programmed sequences circulating cleaning solutions through equipment at specified temperatures, concentrations, flow rates, and durations. Typical sequences include pre-rinse removing bulk product residue, caustic wash removing organic soils, intermediate rinse, acid wash removing mineral deposits, final rinse, and optional sanitization before production resumption.

// CIP Sequence Control for Filling Machine
// Siemens S7-1500 SCL

PROGRAM FillerCIPControl
VAR
    // CIP mode selection
    CIPMode : INT := 0;              // 0=Off, 1=Auto CIP, 2=Manual
    CIPStart : BOOL;                 // Start automatic CIP

    // State machine
    State : INT := 0;
    StateDescription : STRING;

    // Valves and pumps
    ProductSupply : BOOL;            // Product supply valve (closed during CIP)
    CIPSupply : BOOL;                // CIP solution supply
    CIPReturn : BOOL;                // CIP return drain
    CIPPump : BOOL;                  // CIP circulation pump

    WaterSupply : BOOL;              // Water supply valve
    CausticSupply : BOOL;            // Caustic solution valve
    AcidSupply : BOOL;               // Acid solution valve
    SanitizerSupply : BOOL;          // Sanitizer valve

    DrainValve : BOOL;               // Drain to waste

    // Heating control
    HeaterEnable : BOOL;             // Solution heater enable
    TargetTemp : REAL;               // Target solution temperature
    ActualTemp : REAL;               // Measured temperature
    TempOK : BOOL;                   // Temperature at setpoint

    // Flow monitoring
    CIPFlowRate : REAL;              // Flow meter reading (L/min)
    MinFlowRate : REAL := 20.0;      // Minimum acceptable flow
    FlowOK : BOOL;

    // Timers and durations
    StepTimer : TON;

    PreRinseDuration : TIME := T#5m;
    CausticWashDuration : TIME := T#15m;
    IntermediateRinseDuration : TIME := T#5m;
    AcidWashDuration : TIME := T#10m;
    FinalRinseDuration : TIME := T#5m;
    SanitizeDuration : TIME := T#10m;

    // Temperature setpoints
    CausticTemp : REAL := 75.0;      // Caustic wash at 75°C
    AcidTemp : REAL := 60.0;         // Acid wash at 60°C
    SanitizeTemp : REAL := 85.0;     // Hot water sanitization

    // Status
    CIPComplete : BOOL;
    CIPFault : BOOL;
    FaultDescription : STRING;

    // Statistics
    CIPCycleCount : INT := 0;
    LastCIPTime : DATE_AND_TIME;

END_VAR

// Automatic CIP sequence
IF CIPMode = 1 THEN
    CASE State OF
        0:  // Idle - waiting for CIP start
            StateDescription := 'Idle - Ready for CIP';

            // Ensure production valves closed
            ProductSupply := FALSE;

            IF CIPStart THEN
                CIPCycleCount := CIPCycleCount + 1;
                State := 10;
            END_IF;

        10: // Pre-rinse with water
            StateDescription := 'Pre-Rinse';

            WaterSupply := TRUE;
            CIPSupply := TRUE;
            CIPPump := TRUE;
            DrainValve := TRUE;

            StepTimer(IN := TRUE,
                     PT := PreRinseDuration,
                     Q => ,
                     ET => );

            // Verify adequate flow
            FlowOK := (CIPFlowRate >= MinFlowRate);

            IF StepTimer.Q THEN
                StepTimer(IN := FALSE);
                WaterSupply := FALSE;
                State := 20;
            END_IF;

            // Fault if inadequate flow
            IF NOT FlowOK THEN
                CIPFault := TRUE;
                FaultDescription := 'Pre-rinse flow fault';
                State := 100;
            END_IF;

        20: // Heat caustic solution and circulate
            StateDescription := 'Caustic Wash';

            CausticSupply := TRUE;
            CIPSupply := TRUE;
            CIPReturn := TRUE;          // Return for recirculation
            DrainValve := FALSE;
            CIPPump := TRUE;

            HeaterEnable := TRUE;
            TargetTemp := CausticTemp;
            TempOK := (ActualTemp >= (TargetTemp - 2.0));

            // Start timer when temperature reached
            IF TempOK THEN
                StepTimer(IN := TRUE,
                         PT := CausticWashDuration,
                         Q => ,
                         ET => );
            END_IF;

            IF StepTimer.Q THEN
                StepTimer(IN := FALSE);
                CausticSupply := FALSE;
                HeaterEnable := FALSE;
                State := 30;
            END_IF;

        30: // Drain caustic solution
            StateDescription := 'Drain Caustic';

            CIPReturn := FALSE;
            DrainValve := TRUE;

            StepTimer(IN := TRUE,
                     PT := T#2m,
                     Q => ,
                     ET => );

            IF StepTimer.Q THEN
                StepTimer(IN := FALSE);
                State := 40;
            END_IF;

        40: // Intermediate rinse
            StateDescription := 'Intermediate Rinse';

            WaterSupply := TRUE;
            CIPSupply := TRUE;
            CIPPump := TRUE;
            DrainValve := TRUE;

            StepTimer(IN := TRUE,
                     PT := IntermediateRinseDuration,
                     Q => ,
                     ET => );

            IF StepTimer.Q THEN
                StepTimer(IN := FALSE);
                WaterSupply := FALSE;
                State := 50;
            END_IF;

        50: // Acid wash circulation
            StateDescription := 'Acid Wash';

            AcidSupply := TRUE;
            CIPSupply := TRUE;
            CIPReturn := TRUE;
            DrainValve := FALSE;
            CIPPump := TRUE;

            HeaterEnable := TRUE;
            TargetTemp := AcidTemp;
            TempOK := (ActualTemp >= (TargetTemp - 2.0));

            IF TempOK THEN
                StepTimer(IN := TRUE,
                         PT := AcidWashDuration,
                         Q => ,
                         ET => );
            END_IF;

            IF StepTimer.Q THEN
                StepTimer(IN := FALSE);
                AcidSupply := FALSE;
                HeaterEnable := FALSE;
                State := 60;
            END_IF;

        60: // Drain acid solution
            StateDescription := 'Drain Acid';

            CIPReturn := FALSE;
            DrainValve := TRUE;

            StepTimer(IN := TRUE,
                     PT := T#2m,
                     Q => ,
                     ET => );

            IF StepTimer.Q THEN
                StepTimer(IN := FALSE);
                State := 70;
            END_IF;

        70: // Final rinse
            StateDescription := 'Final Rinse';

            WaterSupply := TRUE;
            CIPSupply := TRUE;
            CIPPump := TRUE;
            DrainValve := TRUE;

            StepTimer(IN := TRUE,
                     PT := FinalRinseDuration,
                     Q => ,
                     ET => );

            IF StepTimer.Q THEN
                StepTimer(IN := FALSE);
                WaterSupply := FALSE;
                State := 80;
            END_IF;

        80: // Optional sanitization
            StateDescription := 'Sanitization';

            // Hot water or chemical sanitization
            WaterSupply := TRUE;
            CIPSupply := TRUE;
            CIPReturn := TRUE;
            CIPPump := TRUE;

            HeaterEnable := TRUE;
            TargetTemp := SanitizeTemp;
            TempOK := (ActualTemp >= (TargetTemp - 2.0));

            IF TempOK THEN
                StepTimer(IN := TRUE,
                         PT := SanitizeDuration,
                         Q => ,
                         ET => );
            END_IF;

            IF StepTimer.Q THEN
                StepTimer(IN := FALSE);
                State := 90;
            END_IF;

        90: // Final drain and complete
            StateDescription := 'Final Drain';

            WaterSupply := FALSE;
            CIPSupply := FALSE;
            CIPReturn := FALSE;
            DrainValve := TRUE;
            HeaterEnable := FALSE;

            StepTimer(IN := TRUE,
                     PT := T#3m,
                     Q => ,
                     ET => );

            IF StepTimer.Q THEN
                StepTimer(IN := FALSE);
                DrainValve := FALSE;
                CIPPump := FALSE;

                CIPComplete := TRUE;
                LastCIPTime := DATE_AND_TIME#2025-12-10-10:30:00;
                State := 0;
            END_IF;

        100: // Fault state
            StateDescription := 'CIP Fault';

            // Disable all CIP operations
            CausticSupply := FALSE;
            AcidSupply := FALSE;
            SanitizerSupply := FALSE;
            HeaterEnable := FALSE;

            // Maintain drain and pump for safety
            DrainValve := TRUE;
            CIPPump := TRUE;

            // Require manual reset

    END_CASE;

END_IF;

END_PROGRAM

CIP programming includes extensive interlocks preventing product contamination from cleaning chemicals, ensuring proper drainage between steps preventing solution mixing, verifying temperature achievement before starting timed cleaning phases, and monitoring flow rates detecting pump failures or valve malfunctions.

CIP Validation and Documentation

Regulatory compliance for food and beverage applications requires documented evidence of effective cleaning. PLC programs log critical CIP parameters including solution temperatures with minimum temperature duration tracking, flow rates throughout sequences, actual step durations, and any fault conditions or operator interventions.

Data logging creates batch records for each CIP cycle exportable to databases or SCADA historians providing traceability and validation documentation. Electronic signatures integrate into CIP systems for GMP-compliant facilities requiring authorized operator approval before production resumption after cleaning.

Chapter 8: Practical Application - Complete 18,000 BPH Water Line

System Architecture Overview

This comprehensive example demonstrates integration of all previous concepts in a complete 18,000 bottles-per-hour water bottling line. The system handles 500ml PET bottles at 300 bottles per minute with integrated control from depalletizer through case packer.

Equipment List and Control Distribution

  • Depalletizer: Dedicated PLC (Siemens S7-1200) - Layer picking, pallet handling
  • Rinser: Integrated with main line PLC - 36-head rotary rinser
  • Filler: Motion controller (Siemens S7-1500T) - 18-head gravity filler
  • Capper: Integrated with filler controller - 6-head rotary capper
  • Labeler: Dedicated servo controller (Omron NJ) - Pressure-sensitive labels
  • Inspector: Vision system (Cognex) - Fill level, cap, label verification
  • Case Packer: Dedicated PLC (Allen-Bradley CompactLogix) - Robotic pick-and-place

Line coordinator PLC (Siemens S7-1500) manages overall system control, recipe management, production tracking, and SCADA communication.

Network Topology

PROFINET IRT network connects all PLCs, servo drives, and I/O stations with 2ms update cycle enabling coordinated control. Separate information network using OPC UA connects to plant SCADA and MES systems.

Ring topology provides network redundancy with automatic reconfiguration if communication cable damage occurs. Managed industrial switches enable network diagnostics and traffic monitoring ensuring reliable communication.

Line Coordination and Recipe Management

// Main Line Coordinator Program
// Siemens S7-1500 SCL

PROGRAM BottlingLineCoordinator
VAR
    // Line control
    LineMode : INT := 0;             // 0=Stop, 1=Auto, 2=Manual, 3=Setup
    LineState : INT := 0;

    LineSpeed : REAL := 300.0;       // Target speed (BPM)
    ActualSpeed : REAL;              // Measured production rate

    MasterPositionAxis : DINT := 0;  // Virtual master position
    MasterVelocity : REAL;           // Calculated master velocity

    // Recipe management
    ActiveRecipe : INT := 1;
    RecipeData : ARRAY[1..20] OF BottleRecipe;

    // Equipment module status
    Depalletizer_Ready : BOOL;
    Depalletizer_Running : BOOL;
    Depalletizer_Fault : BOOL;

    Rinser_Ready : BOOL;
    Rinser_Running : BOOL;

    Filler_Ready : BOOL;
    Filler_Running : BOOL;
    Filler_Fault : BOOL;

    Capper_Ready : BOOL;
    Capper_Running : BOOL;

    Labeler_Ready : BOOL;
    Labeler_Running : BOOL;

    Inspector_Ready : BOOL;
    Inspector_Running : BOOL;

    Packer_Ready : BOOL;
    Packer_Running : BOOL;

    // Production counters
    BottlesProduced : DINT := 0;
    BottlesRejected : DINT := 0;
    CasesPacked : DINT := 0;

    // Shift tracking
    ShiftStartTime : DATE_AND_TIME;
    ShiftProduction : DINT := 0;

    // OEE tracking
    PlannedProductionTime : REAL;
    ActualRunTime : REAL;
    Downtime : REAL;
    OEE : REAL;

END_VAR

TYPE BottleRecipe :
STRUCT
    RecipeName : STRING[40];
    RecipeID : INT;

    BottleType : STRING[20];
    BottleHeight : REAL;
    BottleWeight : REAL;

    FillVolume : REAL;
    FillTolerance : REAL;
    TargetFillLevel : REAL;

    CapType : STRING[20];
    CapTorque : REAL;

    LabelType : STRING[20];
    LabelLength : REAL;
    LabelOffset : REAL;

    LineSpeed : REAL;
    BottleSpacing : REAL;

    ConveyorPressure : REAL;

END_STRUCT;
END_TYPE;

// Load active recipe parameters
RecipeData[1].RecipeName := '500ml Water Bottle';
RecipeData[1].RecipeID := 1;
RecipeData[1].BottleHeight := 205.0;
RecipeData[1].FillVolume := 500.0;
RecipeData[1].FillTolerance := 5.0;
RecipeData[1].TargetFillLevel := 190.0;
RecipeData[1].CapTorque := 15.0;
RecipeData[1].LabelLength := 120.0;
RecipeData[1].LineSpeed := 300.0;
RecipeData[1].BottleSpacing := 160.0;
RecipeData[1].ConveyorPressure := 0.25;

// Calculate master velocity from target line speed
// Master axis in mm, velocity in mm/min
MasterVelocity := LineSpeed * RecipeData[ActiveRecipe].BottleSpacing;

// Increment virtual master position
MasterPositionAxis := MasterPositionAxis +
    REAL_TO_DINT(MasterVelocity / 60.0);  // Convert to mm/sec scan rate

// Main line state machine
CASE LineState OF
    0:  // Stopped
        IF LineMode = 1 AND All_Equipment_Ready() THEN
            LineState := 10;
        END_IF;

    10: // Starting sequence
        // Start equipment in upstream-to-downstream order
        Depalletizer_Running := TRUE;

        // Wait for bottles to reach rinser
        // Then start rinser, filler, etc.

        LineState := 20;

    20: // Running
        // All equipment running
        // Monitor production and equipment status

        IF LineMode = 0 THEN
            LineState := 30;  // Shutdown sequence
        END_IF;

    30: // Shutdown sequence
        // Stop equipment in downstream-to-upstream order
        // Ensuring all bottles clear the line

        LineState := 0;

END_CASE;

END_PROGRAM

Complete System Integration

The complete bottling line demonstrates advanced integration techniques including distributed control with peer-to-peer communication, virtual master axis synchronizing all equipment, recipe-based parameter management, coordinated startup and shutdown sequences, comprehensive fault handling, and production data collection for OEE calculation.

This 18,000 BPH line represents typical mid-range bottling automation requiring sophisticated programming but achievable with current PLC technology and proper application engineering.

Chapter 9: Best Practices and Optimization

Bottling Line Commissioning Strategies

Successful bottling line commissioning requires methodical approaches ensuring each subsystem operates correctly before integration testing. Commission equipment modules individually verifying mechanical installation, sensor calibration, and basic control functions before attempting coordinated line operation.

Phased Commissioning Approach

Phase 1 focuses on standalone equipment testing without product or line coordination. Verify I/O functionality, actuator operation, sensor responses, and safety interlocks for each machine independently.

Phase 2 introduces equipment integration testing coordinated motion, communication between controllers, and synchronization timing. Use empty bottles or test containers avoiding product waste during troubleshooting.

Phase 3 validates production operation with actual product at gradually increasing speeds. Begin at 50% design speed, resolve any issues, then incrementally increase speed approaching rated capacity.

Phase 4 optimizes performance through tuning servo systems for smooth motion, adjusting timing parameters minimizing cycle time, and fine-tuning quality inspection thresholds.

OEE Optimization for Beverage Production

Overall Equipment Effectiveness optimization focuses on three components: maximizing availability through minimizing unplanned downtime, optimizing performance through achieving rated speed, and maintaining quality through reducing rejects.

Availability Improvement Strategies

Preventive maintenance schedules based on equipment manufacturers' recommendations prevent unexpected failures. Automated monitoring detecting abnormal conditions enables predictive maintenance replacing components before failure.

Quick changeover procedures minimize planned downtime through recipe-based automation, servo-adjusted mechanical components, and practiced operator procedures achieving changeover times under 10 minutes.

Performance Optimization

Line balancing ensures no equipment module limits overall throughput. Identify bottleneck equipment through production monitoring and increase capacity through equipment upgrades or process optimization.

Speed optimization incrementally increases line speed while monitoring quality, mechanical stress, and reject rates. Many bottling lines operate below rated capacity due to conservative initial settings offering optimization opportunities.

Quality Enhancement

Statistical process control identifies quality trends before systematic problems develop. Trend analysis enables corrective actions preventing quality excursions.

Vision inspection threshold optimization balances false reject rates against acceptance of marginal products. Periodic calibration verification ensures inspection systems maintain accuracy specifications.

Frequently Asked Questions

What PLC is best for bottling lines?

The optimal PLC for bottling line applications depends on line complexity, speed requirements, and motion control needs. For small to medium lines (under 300 BPM), Siemens S7-1500 series or Allen-Bradley ControlLogix L7 controllers provide comprehensive capabilities including integrated motion control, PROFINET or EtherNet/IP communication, and sufficient program memory for complex applications ($8,000-$15,000 complete system). High-speed lines exceeding 600 BPM benefit from specialized motion controllers like Omron NJ/NX series with EtherCAT communication providing sub-millisecond control cycles, or Beckhoff TwinCAT PC-based controllers offering extreme performance for 100+ axis applications ($12,000-$30,000+). European bottling equipment predominantly uses Siemens platforms, while North American installations favor Allen-Bradley creating regional preferences affecting maintenance and support considerations. Multi-machine lines benefit from distributed architectures using mid-range PLCs for individual machines (S7-1200, CompactLogix) coordinated through industrial Ethernet reducing single-point failure risk.

How do you synchronize multiple machines in bottling?

Bottling line synchronization uses electronic line shaft architecture where a virtual master axis representing overall line position drives all physical conveyor and rotary machine axes through electronic gearing. The master axis can be a virtual position incremented by the PLC based on line speed setpoint or a physical encoder mounted on a primary conveyor. Each machine calculates its electronic gear ratio from mechanical specifications and recipe parameters: star wheel ratios = (pocket angle) / (bottle spacing), conveyor ratios = (conveyor distance per master distance), filler carousel ratios = (carousel degrees per bottle). PLCs implement synchronization through motion control function blocks (MC_GearIn for Siemens/Omron, MAG for Allen-Bradley) engaging electronic gearing when equipment starts. This approach eliminates mechanical drive shafts while providing perfect synchronization, accommodating speed changes without reprogramming, enabling quick changeovers through recipe-based ratio changes, and allowing individual machine positioning for maintenance without disconnecting mechanical drives.

What is electronic filling and how is it programmed?

Electronic filling uses electronically controlled valves (solenoid valves, servo-driven valves, or pneumatic valves with electronic actuation) instead of mechanical cam-driven fill valve timing. Programming controls valve opening/closing with millisecond precision based on bottle position, carousel angle, or elapsed time. Simple time-based electronic filling calculates fill duration from target volume, product characteristics, and process conditions (temperature, pressure) compensating for variables through sensor feedback. Advanced mass flow systems integrate flow meters providing closed-loop control opening valves until measured dispensed mass reaches targets (±0.1% accuracy). Multi-stage filling algorithms optimize speed and accuracy: fast fill to 90% of target using large orifice, slow fill to 98% for precision approach, dribble fill to exact target using minimal flow or pulsed valve control. Electronic filling provides flexibility for product changes without mechanical adjustments, precise volume control through programmable parameters, data collection for SPC and traceability, and adaptive control learning fill-in-flight characteristics and automatically compensating. Programming uses state machines sequencing fill phases, PID control for flow-based systems, temperature and pressure compensation algorithms, and fault detection identifying timeout or abnormal flow conditions.

How do you program CIP sequences?

CIP (Clean-in-Place) programming automates cleaning sequences circulating solutions through equipment at controlled temperatures, concentrations, and durations without disassembly. Programs use state machine architecture progressing through cleaning phases: pre-rinse removing bulk product (water, 3-5 minutes), caustic wash removing organic soils (1-2% NaOH, 70-80°C, 10-15 minutes), intermediate rinse removing caustic residue, acid wash removing mineral scale (1-2% HNO3 or H3PO4, 60°C, 5-10 minutes), final rinse ensuring no chemical residue, and sanitization with hot water (>85°C) or chemical sanitizer. Programming controls solution selection valves, recirculation pumps, temperature through heater control with PID regulation, timing through TON timers for each phase, flow monitoring detecting circulation problems, and drainage between phases preventing solution mixing. Interlocks prevent production operations during CIP, require operator confirmation before chemical dispensing, monitor minimum temperatures before starting timed cleaning phases, verify adequate flow rates throughout sequences, and log all parameters for regulatory documentation. Automated CIP reduces cleaning time from hours to 45-90 minutes, ensures consistent cleaning effectiveness, provides documented validation, reduces water and chemical consumption, and enables lights-out operation of extended production schedules.

What sensors are used in bottling?

Bottling lines use diverse sensor types: photoelectric through-beam sensors detect bottle presence on conveyors and count production (response time <0.5ms for high-speed lines), diffuse photoelectric sensors verify cap presence and detect label edges, fiber optic sensors with remote amplifiers enable detection in confined spaces around rotary equipment, proximity sensors verify metal cap presence and detect fill nozzle positions, encoders (2000-10000 PPR incremental encoders) track conveyor position for product registration and motion synchronization, vision systems inspect fill levels, cap orientation, label placement, and read barcodes/date codes, load cells (0.1% accuracy) measure fill weights in weight-based filling systems, flow meters (turbine, electromagnetic, Coriolis) measure dispensed volumes in volumetric filling, pressure transducers (0-10 bar range) monitor filling pressure, air conveyor pressure, and CIP circulation pressure, and temperature sensors (RTD or thermocouple) control CIP solution temperatures, monitor product temperature, and verify pasteurization processes. Sensor selection criteria include response speed adequate for line rates, IP67 washdown-rated enclosures for hygienic environments, FDA-compliant materials for product-contact sensors, and IO-Link communication enabling advanced diagnostics and parameter adjustment.

How do you track bottles through the line?

Product tracking follows individual bottles from infeed through final packing enabling reject diversion, quality data association, and serialization for regulatory compliance. Encoder-based tracking uses high-speed counters accumulating encoder pulses representing precise conveyor travel distance with bottle positions calculated from encoder counts and known bottle spacing. Program arrays or FIFO queues store product attributes (quality status, fill weight, inspection results, serial numbers) indexed by position. As bottles advance, tracking data shifts through arrays matching physical product movement. Actions (inspection triggering, reject diversion, labeling) execute when product position calculations indicate bottles reaching action points. Alternative time-based tracking calculates position from elapsed time and conveyor speed suitable for constant-speed applications but less accurate during speed changes or brief stops. Advanced tracking systems accommodate mixed products in single line flow associating different recipe parameters with individual bottles enabling simultaneous production of multiple SKUs. Registration-based tracking uses vision or mark sensors detecting actual product positions correcting theoretical position calculations for accumulated mechanical errors. Proper tracking requires accurate bottle spacing measurements, precise encoder mounting and calibration, careful timing of product detection sensors, and regular verification comparing predicted versus actual product positions at test points.

What communication protocols are used?

Modern bottling lines use industrial Ethernet protocols for real-time control communication and standard Ethernet for information systems. PROFINET IRT (Isochronous Real-Time) dominates European bottling equipment providing deterministic communication with 250μs-4ms update cycles, extensive Siemens integration, broad device support from European equipment manufacturers, and conformance class C certification for critical applications. EtherNet/IP with CIP Motion suits North American installations through Rockwell Automation ecosystem integration, motion control capabilities adequate for most bottling speeds (1-2ms typical cycle times), ODVA standard ensuring multi-vendor compatibility, and strong presence in food and beverage industries. EtherCAT provides highest performance for demanding applications with <100μs cycle times, <1μs jitter for precise synchronization, extensive servo drive support from major manufacturers, and PC-based controller compatibility. Networks use ring topology with media redundancy (MRP for PROFINET, DLR for EtherNet/IP) providing <200ms failover if cable damage occurs. Information level uses OPC UA for standardized PLC-to-SCADA communication, database gateways for production data collection, MQTT for IoT and cloud integration, and web servers in modern PLCs enabling browser-based HMI access without specialized software.

How do you integrate vision inspection?

Vision system integration coordinates PLC control with vision processors for quality inspection at production speeds. Simple discrete I/O integration uses vision system discrete outputs signaling inspection results (pass/fail, specific defect detection) to PLC inputs adequate for basic fill level checking and cap presence verification. Industrial Ethernet integration via EtherNet/IP, PROFINET, or Ethernet TCP/IP enables comprehensive communication including trigger signals from PLC synchronized with product position using encoders ensuring consistent image capture locations, detailed inspection results with measurement values and defect classifications, product changeover commands sending recipe information configuring inspection parameters automatically, and diagnostic data for vision system health monitoring and performance trending. PLC programming manages trigger generation from encoder position or product detection sensors with delay compensation ensuring correct bottle positioning at camera field of view, result processing interpreting multiple inspection criteria through logical operations generating overall accept/reject decisions, reject diversion commanding pneumatic gates or pushers removing defective products, and data logging recording inspection statistics for SPC analysis and quality reporting. Vision system selection balances speed requirements (minimum exposure time and image processing duration), resolution needed for defect detection, lighting considerations for stable imaging, and communication capabilities supporting required PLC integration depth. Smart cameras with integrated processing suit simpler applications while PC-based vision systems provide advanced capabilities for complex multi-camera inspections.

What is OEE in bottling?

Overall Equipment Effectiveness (OEE) measures bottling line productivity through three multiplied components: Availability = (Operating Time) / (Planned Production Time) accounting for downtime from breakdowns, changeovers, and stoppages; Performance = (Actual Production) / (Theoretical Maximum Production) accounting for speed losses from running below rated capacity or minor stops; and Quality = (Good Product) / (Total Production) accounting for rejects and quality losses. OEE = Availability × Performance × Quality expressed as percentage with world-class bottling targets exceeding 85% though actual industry averages range 60-75%. Tracking requires time-based data collection distinguishing planned production time, actual run time, categorized downtime (mechanical failures, changeovers, material shortages, quality issues), count-based production data tracking total bottles processed and good bottles produced with rejects categorized by reason, and speed monitoring comparing actual production rates versus equipment-rated speeds identifying performance gaps. Bottling-specific OEE challenges include frequent product changeovers reducing availability (mitigated through SMED quick-changeover techniques), quality sensitivity where small fill deviations create rejects (addressed through SPC and process control), and high-speed operation where minor stops accumulate significant losses (reduced through preventive maintenance and operator training). OEE improvement prioritizes largest loss contributors through Pareto analysis, implements targeted countermeasures, and monitors trending verifying improvement sustainability.

How do you program recipe management?

Recipe management systems enable rapid product changeovers storing complete parameter sets for different bottle types, products, and customer requirements. Define structured data types containing all recipe-dependent parameters: product identification (name, code, customer), bottle specifications (height, diameter, weight, material), fill parameters (volume/weight, tolerance, fill algorithm settings), motion parameters (line speed, bottle spacing, star wheel ratios, servo positions), capping parameters (cap type, torque setpoint, tightening profile), labeling parameters (label dimensions, application offset, registration tolerances), inspection parameters (fill level targets, vision thresholds), and process parameters (conveyor pressures, temperatures, timing values). Create arrays of recipe structures storing multiple products (Recipe[1..50] accommodating 50 product variations). Implement recipe selection through HMI providing product lists with search/filter capabilities, loading operations transferring selected recipe from persistent storage (PLC memory, SD card, or network database) into active working variables controlling equipment, validation preventing invalid parameter combinations (bottle height exceeding equipment limits, fill volume incompatible with bottle capacity), and security restricting recipe modification through user access levels and password protection. Advanced features include automatic changeover sequences coordinating mechanical adjustments with parameter loading guiding operators through required manual changes while automatically configuring programmable parameters, recipe optimization using production data and quality feedback automatically adjusting parameters improving fill accuracy or line speed, and version control tracking parameter changes over time maintaining audit trails for regulated environments. Recipe development combines equipment manufacturer specifications, product testing validating quality at various speeds, and optimization trials identifying optimal parameter combinations balancing speed, quality, and efficiency.

Conclusion: Mastering Beverage Production Automation

Bottling line PLC programming represents sophisticated industrial automation combining high-speed motion control, precision filling algorithms, coordinated multi-machine synchronization, quality inspection integration, and hygienic process management. Success requires mastering fundamental PLC programming concepts while developing specialized knowledge of beverage industry requirements, equipment technologies, and process control techniques specific to bottling applications. The comprehensive knowledge presented in this guide provides the foundation needed to design, program, commission, and optimize modern bottling automation systems meeting demanding requirements for production speed, fill accuracy, quality consistency, and regulatory compliance.

The beverage industry continues evolving with increasing line speeds pushing control system performance limits, growing automation of manual operations including format changeovers and equipment cleaning, expanding integration of Industry 4.0 technologies for predictive maintenance and production optimization, and higher flexibility demands supporting smaller batch sizes and rapid product transitions. Engineers developing expertise in bottling line programming position themselves for rewarding careers with beverage manufacturers, bottling equipment OEMs, system integrators serving the beverage industry, and specialized automation companies providing engineering services globally.

Practical experience remains essential for developing true proficiency in bottling automation. Apply the concepts, examples, and programming techniques from this guide to actual bottling projects, starting with simpler filling or labeling machines and progressively tackling complete integrated lines as skills develop. Study existing bottling programs, participate in commissioning activities, troubleshoot production issues, and learn from experienced beverage automation engineers. The combination of theoretical knowledge from this guide and hands-on practical experience creates the comprehensive expertise required for success in the dynamic and technically demanding field of beverage production automation.

For further learning, explore related topics including Packaging Machine PLC Programming for broader packaging automation context, Omron PLC Programming Tutorial for platforms popular in beverage applications, PROFINET Tutorial for industrial Ethernet communication fundamentals, SCADA Best Practices for production monitoring systems, and PLC Programming Best Practices for professional development standards applicable across all automation domains including beverage production.

💡 Pro Tip: Download Our Complete PLC Programming Resource

This comprehensive 12 870-word guide provides deep technical knowledge, but our complete 500+ page guide (coming December 2025) includes additional practical exercises, code templates, and industry-specific applications.Preorder the complete guide here (60% off) →

🚧 COMING DECEMBER 2025 - PREORDER NOW

🚀 Ready to Become a PLC Programming Expert?

You've just read 12 870 words of expert PLC programming content. Preorder our complete 500+ page guide with even more detailed examples, templates, and industry applications.

500+ Pages
Expert Content
50+ Examples
Real Applications
60% Off
Preorder Price
Preorder Complete Guide - $47

✓ December 2025 release ✓ Full refund guarantee

#bottlingautomation#beverageindustry#fillingmachines#cipautomation#visioninspection#high-speedpackaging
Share this article:

Frequently Asked Questions

How long does it take to learn PLC programming?

With dedicated study and practice, most people can learn basic PLC programming in 3-6 months. However, becoming proficient in advanced techniques and industry-specific applications typically takes 1-2 years of hands-on experience.

What's the average salary for PLC programmers?

PLC programmers earn competitive salaries ranging from $55,000-$85,000 for entry-level positions to $90,000-$130,000+ for senior roles. Specialized expertise in specific industries or advanced automation systems can command even higher compensation.

Which PLC brands should I focus on learning?

Allen-Bradley (Rockwell) and Siemens dominate the market, making them excellent starting points. Schneider Electric, Mitsubishi, and Omron are also valuable to learn depending on your target industry and geographic region.

Related Articles

🚧 COMING DECEMBER 2025 - PREORDER NOW

Ready to Master PLC Programming?

Be among the first to get our comprehensive PLC programming guide. Preorder now and save 60% off the final price!

500+
Pages of Expert Content
50+
Real-World Examples
60% Off
Preorder Discount
Preorder PLC Programming Guide - $47

✓ December 2025 Release ✓ Full Refund Guarantee ✓ Exclusive Preorder Benefits