Click the blue text
PLC Automation Exchange
Follow us
In the field of industrial automation, the cumulative flow statistics of flow meters is a common and important requirement. How can we accurately and reliably calculate the total flow in the face of fluctuating instantaneous flow signals? Today, we bring you a practical SCL function block solution.
Problem Analysis
Flow meters typically output a 4-20mA analog signal, which the PLC reads and converts into an instantaneous flow value. Due to the dynamic characteristics of the process, this instantaneous flow is often fluctuating. To calculate the total flow, we need to perform a time integral of the instantaneous flow:
Total Flow = ∫ Instantaneous Flow × dt
Complete Code for the SCL Function Block
FUNCTION_BLOCK FB_FlowAccumulator
VAR_INPUT
b_Reset: BOOL; // Reset signal for cumulative value
r_InstantaneousFlow: REAL; // Instantaneous flow input signal
t_SamplingTime: TIME := T#1S; // Calculation sampling time
END_VAR
VAR_OUTPUT
r_CumulativeFlow: REAL; // Cumulative flow value
r_CurrentFlow: REAL; // Current instantaneous flow value
w_StatusWord: WORD; // System status indication
i_LoopCount: UDINT; // Number of execution loops
END_VAR
VAR
t_LastTime: TIME; // Last calculation timestamp
b_InitializationComplete: BOOL; // Initialization status flag
r_TemporaryCumulative: LREAL; // High precision temporary cumulative value
i_InternalCount: UDINT; // Internal loop counter
END_VAR
VAR CONSTANT
r_MaxFlow: REAL := 10000.0; // Upper limit of reasonable flow range
END_VAR
// ========== Flow Accumulation Calculation Method ==========METHOD CalculateFlowTotal : BOOL
VAR_INPUT
r_InputFlow: REAL;
END_VAR
VAR
t_TimeDifference: TIME;
r_TimeDifferenceSeconds: REAL;
r_FlowIncrement: LREAL;
t_CurrentTime: TIME;
END_VAR
// Initialization Check
IF NOT b_InitializationComplete THEN
t_LastTime := TIME();
b_InitializationComplete := TRUE;
r_CumulativeFlow := 0.0;
r_TemporaryCumulative := 0.0;
RETURN TRUE;
END_IF;
// Get Current System Time
t_CurrentTime := TIME();
// Calculate Time Interval
IF t_CurrentTime >= t_LastTime THEN
t_TimeDifference := t_CurrentTime - t_LastTime;
ELSE
// Handle system time anomaly
t_TimeDifference := t_LastTime - t_CurrentTime;
END_IF;
// Convert Time Unit to Seconds
r_TimeDifferenceSeconds := TIME_TO_REAL(t_TimeDifference) / 1000.0;
// Input Validity Check
IF r_InputFlow < 0.0 THEN
w_StatusWord := 16#0001; // Negative flow warning
r_InputFlow := 0.0;
ELSIF r_InputFlow > r_MaxFlow THEN
w_StatusWord := 16#0002; // Overrange warning
r_InputFlow := r_MaxFlow;
ELSE
w_StatusWord := 0; // Normal status
END_IF;
// Calculate Flow Increment: Flow × Time
r_FlowIncrement := r_InputFlow * r_TimeDifferenceSeconds;
// Accumulate to Total Flow
r_TemporaryCumulative := r_TemporaryCumulative + r_FlowIncrement;
// Update Output Values
r_CumulativeFlow := LREAL_TO_REAL(r_TemporaryCumulative);
r_CurrentFlow := r_InputFlow;
// Update Timestamp and Counter
t_LastTime := t_CurrentTime;
i_InternalCount := i_InternalCount + 1;
i_LoopCount := i_InternalCount;
RETURN TRUE;
END_METHOD
// ========== Main Program ==========IF b_Reset THEN
// Reset all cumulative values and status
r_CumulativeFlow := 0.0;
r_TemporaryCumulative := 0.0;
r_CurrentFlow := 0.0;
t_LastTime := TIME();
i_InternalCount := 0;
i_LoopCount := 0;
w_StatusWord := 0;
b_InitializationComplete := FALSE;
ELSE
// Execute Flow Accumulation Calculation
CalculateFlowTotal(r_InstantaneousFlow);
END_IF;
END_FUNCTION_BLOCK
Function Block Usage Example
// Instantiate Function Block
VAR
FB_FlowCalculation : FB_FlowAccumulator;
END_VAR
// Call in Main Loop
FB_FlowCalculation(
b_Reset := "Reset Button", // Connect reset button
r_InstantaneousFlow := "AI_FlowMeter", // Connect flow meter analog input
t_SamplingTime := T#100MS // Set 100ms sampling period
);
// Read Calculation Results
"Display_CumulativeFlow" := FB_FlowCalculation.r_CumulativeFlow;
"Display_InstantaneousFlow" := FB_FlowCalculation.r_CurrentFlow;
"Display_Status" := FB_FlowCalculation.w_StatusWord;
Function Block Features Explained
1. High Precision Calculation
-
Uses
<span><span>r_TemporaryCumulative</span></span>(LREAL type) for intermediate calculations to avoid cumulative errors -
Automatic time compensation to adapt to different PLC scan cycles
2. Comprehensive Exception Handling
-
Negative Flow Detection: Automatically resets to zero and alarms when negative flow is detected
-
Overrange Protection: Automatically limits flow when it exceeds the set upper limit
-
Time Anomaly Handling: Handles special cases such as system time reversal
3. Flexible Reset Mechanism
-
Can reset and re-accumulate at any time via
<span><span>b_Reset</span></span>signal -
All related variables are correctly initialized upon reset
4. Status Monitoring
-
<span><span>w_StatusWord</span></span>provides detailed system status information -
<span><span>i_LoopCount</span></span>records the number of function block executions for debugging purposes
Project Application Recommendations
1. Sampling Time Selection
// Choose appropriate sampling time based on flow fluctuation frequency
t_SamplingTime := T#50MS; // For rapid fluctuations
t_SamplingTime := T#1S; // For general applications
t_SamplingTime := T#5S; // For slow changes
2. Power Failure Protection Implementation
// Store critical data in retain memory
VAR RETAIN
r_CumulativeFlow_Retain: REAL;
END_VAR
3. Flow Filtering Processing
If the flow signal has significant noise, it is recommended to add a moving average filter before input:
// Simple moving average filter example
r_InstantaneousFlow_Filtered := (r_InstantaneousFlow + r_LastFlow1 + r_LastFlow2) / 3.0;
Conclusion
This SCL function block provides a stable and reliable flow accumulation solution with the following advantages:
-
✅ High Precision: Reduces cumulative errors
-
✅ Robust: Comprehensive exception handling mechanism
-
✅ Easy to Use: Clear interfaces and status indications
-
✅ Scalable: Facilitates functional expansion and customization
Suitable for various industrial scenarios requiring precise flow accumulation, such as water treatment, chemical processing, and energy management.
Try this function block now to make your flow statistics more accurate and reliable!
Feel free to leave your experiences in the comments or share your improvement suggestions!
【🔥 Don’t leave without supporting us!】
This informative article took a lot of effort to compile, if it has helped or inspired you, please be sure to:
❶ Leave your thoughts in the “Comments” section ➠ Have you encountered similar issues? Do you have better methods? We look forward to your insights!
❷ Share it with more people in need ➠ Perhaps your friends are struggling with the same problem!
❸ Bookmark it for future reference ➠ Knowledge points need to be digested repeatedly, save it to avoid getting lost!
Every interaction is our motivation to continue creating quality content!💪 Thank you for being with us on this journey!
Recommended Reading:
- Exerting all efforts! Nine-step guide to stable operation of Siemens PLC
- Siemens S7-1500 PLC Troubleshooting: Transform into an industrial “doctor” to quickly “cure” production line downtime!
- [10 Years of Siemens PLC Veteran Upgrade Path] From screwing modules to mastering communication architecture: My blood and tears technical stack guide
- Three “weapons” of servo motors: Detailed explanation of position/velocity/torque control (with practical Siemens SCL code)
- Core Secrets of Siemens PLC Programming: What are FB, FC, DB, OB? You will understand after reading this!
- Why can’t PLC engineers with a monthly salary of 20,000 retain talent? The “career burnout” behind high salaries is consuming this industry!
- Siemens PLC Programming: Ladder Diagram vs SCL, which one is for you? A beginner’s guide with practical code!
- Say goodbye to “spaghetti code”! Siemens PLC sequential programming “three-step method”, double efficiency without pitfalls!
- Siemens SCL communication heartbeat monitoring: A practical guide to industrial-grade heartbeat programs
- Siemens 1200 and Weintek tag communication: Say goodbye to manual address filling, this “smart translator” speeds up debugging by 3 times!
- Siemens SCL Practical: A step-by-step guide to writing station control function blocks
- Siemens S7-1200 Mixed Programming Practical: The golden combination rules of SCL and LAD
- Electrical Automation Encirclement: A decade of hard work brings this heartfelt industry experience summary
- Siemens SCL workstation control program: Start-stop control + three-color light + buzzer alarm
- Mitsubishi FX3U PLC Dual Pump Constant Pressure Water Supply Explained: Intelligent switching between frequency and power frequency + safety emergency stop system
- Electrical Automation Professional Graduation Guide:
- Employment direction and salary prospects fully analyzed
- Electrical Automation Associate Graduates: Starting salaries not inferior to undergraduates? Full disclosure of the technical counterattack roadmap!
- Siemens S7-200 SMART Free Port Communication Explained: Introduction to flexible serial communication solutions
- Ultimate Siemens SCL Full-Function Servo Control Solution: 8 Motion Modes + 5 Safety Protections
- Let data speak! A scientific guide for choosing majors: Science vs Humanities (with employment salary & trend analysis)
Sharing lets more people see it

Like
Bookmark
Share