WinCC Flexible Calculator VBScript Implementation Guide for MP370

David Krause13 min read
SiemensTutorial / How-toWinCC
Licensed PE Working through this on a live machine? A Maine-licensed engineer can take it from here — included with IMD hardware, by the hour for everything else. Book an engineer

Overview

Adding a basic arithmetic calculator to a Siemens MP370 panel running WinCC Flexible 2007 is a common request when an operator needs ad-hoc math without leaving the HMI runtime. WinCC Flexible supports VBScript as an embedded scripting language that runs inside the Smart/Windows CE / Windows-based runtime of the MP 370 family. This reference shows how to design the tags, build the screen, write the script, handle operator input errors, deploy the project, and verify the runtime behavior on the panel.

The MP 370 12" and 15" touch panels ship in two main variants:

  • MP 370 12" Touch with 12.1" TFT, 800 x 600 resolution.
  • MP 370 15" Touch with 15.1" TFT, 1024 x 768 resolution.

Both run WinCC Flexible Runtime and support the VBScript model used here. The method below targets the on-panel runtime, but the same project runs unchanged in the WinCC Flexible RT simulator on the engineering PC.

Prerequisites

Before starting, confirm the following are available on the engineering station:

  • WinCC Flexible 2007 SP3 or later (SP5 recommended for MP 370 compatibility patches). Confirm with the Siemens Industry Online Support compatibility list before commissioning.
  • Microsoft VBScript runtime 5.6 or later installed on the engineering PC (default on Windows XP / Windows 7 SP1).
  • MP 370 panel with operating system image supporting WinCC Flexible 2007 RT. The MP 370 must have its ProSave image compatible with the WinCC Flexible 2007 build you are using.
  • Ethernet or serial (MPI/PROFIBUS) connection between the engineering PC and the MP 370 for project transfer.
  • An empty HMI tag namespace or a clearly separated tag prefix (for example Calc_) so the calculator variables do not collide with process tags.
Notice: VBScript on WinCC Flexible is interpreted at runtime and does not require the full Visual Studio / VB IDE on the panel. The PC only needs the runtime DLLs that ship with the OS image.

MP370 Runtime Limits Relevant to a Calculator

The MP 370 runtime imposes a few constraints that shape the script design. The following table lists the practical limits to design against. Values shown are typical for the WinCC Flexible 2007 RT image; verify against the specific build of your panel if running in production.

Parameter MP 370 12" Touch MP 370 15" Touch
Display resolution 800 x 600 1024 x 768
Colors 64 k colors 64 k colors
Touch Analog resistive Analog resistive
Processor class 32-bit RISC 32-bit RISC
User memory Order-dependent (12 MB / 24 MB options) Order-dependent (12 MB / 24 MB options)
VBScript support Yes (WinCC Flexible RT) Yes (WinCC Flexible RT)
Recommended RT build WinCC Flexible 2007 SP3+ WinCC Flexible 2007 SP3+
Max I/O fields per screen Project-bound, not panel-bound Project-bound, not panel-bound
Notice: Exact user-memory size depends on the MLFB (ordering number) of your MP 370. Check the rating plate or the Siemens product support page before loading large projects.

WinCC Flexible VBScript Architecture

WinCC Flexible scripts run in three contexts:

  1. Tag-triggered — fires when a configured tag changes value.
  2. Event-triggered — fires on a button press, screen change, or value change on an I/O field.
  3. Cyclical / scheduled — fires on a configured tick (typical 250 ms / 500 ms / 1 s increments).

For a calculator, the most natural fit is event-triggered: pressing the equals button (=) computes the result. You can also trigger on the operator pressing the numeric keypad's Enter key. Avoid pure cyclical execution for a calculator — it will consume CPU on a panel that already has real-time HMI duties.

The VBScript runtime on the panel exposes a subset of the Windows scripting host. The calculator only needs a small surface:

Function Purpose
SmartTags("name") Read / write HMI tag value
CDbl(expression) Convert to IEEE-754 double precision
CStr(expression) Convert to string for display
IsNumeric(expr) Validate input
Replace(str, find, repl) Strip operator glyphs
MsgBox(text, type, title) Show error popup on panel

Tag Configuration

Create the following internal tags under HMI Tags > Internal Tags in the WinCC Flexible project. Internal tags are stored in the panel's RAM and require no PLC connection. Use the Calc_ prefix to keep them isolated from process tags.

Tag name Data type Length / range Initial value Role
Calc_OperandA Real (Float) IEEE-754 double, 8 bytes 0.0 First operand
Calc_OperandB Real (Float) IEEE-754 double, 8 bytes 0.0 Second operand
Calc_Result Real (Float) IEEE-754 double, 8 bytes 0.0 Computed result
Calc_Operator String 1 char (WString 2 bytes) "+" Pending operator: + - * /
Calc_Display String 32 chars "0" On-screen display text
Calc_Error Bool 1 bit 0 Error latch for visibility
Calc_LastKey String 1 char "" Diagnostic echo
Notice: VBScript on WinCC Flexible represents doubles with full 64-bit IEEE-754 precision but display rounding can hide NaN/Inf states. Always validate with IsNumeric and Not IsNaN before assigning to Calc_Result.

Screen Layout Design

Add a new screen called Screen_Calculator to the project. Recommended layout for an MP 370 15":

  • Display field: I/O field bound to Calc_Display, aligned right, large font (24 pt), monospace.
  • Numeric keypad: Buttons 0–9 and the decimal point, each setting a temporary input tag via the Click event.
  • Operator buttons: +, -, *, / - each stores the pending operator and saves the current entry as Calc_OperandA.
  • Equals button: calls Calc_Compute to evaluate the pending operation.
  • Clear button: resets all tags and the display.
  • Backspace button: removes the last character from Calc_Display.

Bind each numeric button's Click event to a small subroutine that appends the digit to the display string. For example, the 1 button:

Sub Num1_Click(ByRef Item)
    Dim s
    s = SmartTags("Calc_Display")
    If s = "0" Then
        s = "1"
    Else
        s = s & "1"
    End If
    SmartTags("Calc_Display") = s
End Sub

Repeat this pattern for digits 0–9. The decimal point uses a similar routine but checks that the display does not already contain a dot before appending one. This prevents operator inputs like 1.2.3 from breaking CDbl.

VBScript Calculator Implementation

Define the following project-wide function in Scripts > Project Functions. Project functions in WinCC Flexible are global to all screens.

Function Calc_Compute()
    Dim a, b, op, r
    Dim sDisplay
    
    sDisplay = SmartTags("Calc_Display")
    
    ' --- Validate operator input ---
    If Not IsNumeric(sDisplay) Then
        SmartTags("Calc_Error") = True
        ShowSystemAlarm "Calculator: invalid input"
        Exit Function
    End If
    
    ' --- Commit current display as operand B ---
    SmartTags("Calc_OperandB") = CDbl(sDisplay)
    a = SmartTags("Calc_OperandA")
    b = SmartTags("Calc_OperandB")
    op = SmartTags("Calc_Operator")
    
    ' --- Evaluate ---
    Select Case op
        Case "+"
            r = a + b
        Case "-"
            r = a - b
        Case "*"
            r = a * b
        Case "/"
            If b = 0 Then
                SmartTags("Calc_Error") = True
                ShowSystemAlarm "Calculator: divide by zero"
                Exit Function
            Else
                r = a / b
            End If
        Case Else
            r = b
    End Select
    
    ' --- Handle special IEEE states ---
    If IsNull(r) Or (VarType(r) = vbError) Then
        SmartTags("Calc_Error") = True
        Exit Function
    End If
    
    ' --- Format and publish ---
    SmartTags("Calc_Result") = r
    SmartTags("Calc_Display") = FormatNumber(r, 6, vbFalse, vbFalse, vbFalse)
    SmartTags("Calc_OperandA") = r
    SmartTags("Calc_OperandB") = 0
    SmartTags("Calc_Operator") = "+"
    SmartTags("Calc_Error") = False
End Function

The equals button's Click event calls this function directly. To allow chained operations (for example 3 + 4 * 2 equals 14, not 11), the function reassigns the result into Calc_OperandA and resets the operator. This implements left-to-right evaluation, which is the operator-friendly default for a basic HMI calculator.

Operator Button Script

The plus, minus, multiply, and divide buttons share the same template. Replace the operator glyph in each case:

Sub OpAdd_Click(ByRef Item)
    Dim s
    s = SmartTags("Calc_Display")
    If IsNumeric(s) Then
        SmartTags("Calc_OperandA") = CDbl(s)
    End If
    SmartTags("Calc_Operator") = "+"
    SmartTags("Calc_Display") = "0"
End Sub

Operators save the currently displayed value into Calc_OperandA, store the chosen operator, and reset the display so the next numeric input lands in operand B.

Clear and Backspace

Sub Clr_Click(ByRef Item)
    SmartTags("Calc_OperandA") = 0
    SmartTags("Calc_OperandB") = 0
    SmartTags("Calc_Result") = 0
    SmartTags("Calc_Operator") = "+"
    SmartTags("Calc_Display") = "0"
    SmartTags("Calc_Error") = False
End Sub

Sub Bksp_Click(ByRef Item)
    Dim s
    s = SmartTags("Calc_Display")
    If Len(s) > 1 Then
        s = Left(s, Len(s) - 1)
    Else
        s = "0"
    End If
    SmartTags("Calc_Display") = s
End Sub

Numeric Parsing and Error Handling

The display string is the only mutable input surface. Treat it as untrusted text. Apply the following checks before any conversion:

  1. IsNumeric(sDisplay) must be True.
  2. The string must contain at most one decimal separator.
  3. The string must not be empty.
  4. If the operator is /, Calc_OperandB must not equal zero.
  5. The result must not be NaN, +Inf, or -Inf.

For step 5, WinCC Flexible VBScript treats NaN as the string "NaN" in some builds, while other builds return Empty. Defensive code therefore uses VarType plus an explicit overflow check:

If (r <> r) Then
    ' IEEE NaN test: NaN is the only value not equal to itself
    SmartTags("Calc_Error") = True
    ShowSystemAlarm "Calculator: result is NaN"
    Exit Function
End If

The expression (r <> r) is the canonical IEEE-754 NaN test and is supported by the VBScript engine shipped with WinCC Flexible 2007 SP3 and later.

Display Formatting

The FormatNumber call in Calc_Compute trims trailing zeros while keeping six fractional digits maximum. For shop-floor readability on the MP 370, you may prefer a coarser rounding:

SmartTags("Calc_Display") = CStr(Round(r, 3))

This caps display precision to 3 decimals and avoids the trailing zeros that confuse operators reading values like 1.500000. If the result is an integer, no decimal point appears, which is the typical calculator behavior.

Notice: The display is a string tag. Operators may see different rounding in the on-screen text than in the floating-point Calc_Result tag. If a downstream PLC tag consumes Calc_Result, use the unrounded double. If the operator just needs a readout, use the formatted string.

Deployment to MP370

  1. In WinCC Flexible, select Project > Transfer > Transfer Settings.
  2. Choose the channel: Ethernet (recommended for 15" panels) or MPI/PROFIBUS via the PC adapter.
  3. Set the MP 370 IP address (default is 192.168.0.1 on many images; verify in the panel's Control Panel under Network).
  4. Set the PC-side IP in the same subnet, for example 192.168.0.10, with subnet mask 255.255.255.0.
  5. Save the project, then Project > Transfer > Transfer to Target System.
  6. Wait for the transfer to complete (12 MB project transfers in roughly 30–90 s over Ethernet at 100 Mbit/s).
  7. Confirm the panel restarts into WinCC Flexible Runtime automatically if the project settings include Start Runtime after transfer.
Notice: If the MP 370 prompts for a password after restart, the default image uses no password. Set a password under Control Panel > Password before commissioning to a production line.

Runtime Verification

After the panel boots, navigate to the calculator screen and run a smoke test sequence:

Step Operator action Expected Calc_Display Pass criterion
1 Press 7 7 Display shows 7
2 Press + 0 (operand A stored as 7) Display clears
3 Press 5 5 Display shows 5
4 Press = 12 Result is 12.0
5 Press * 0 Display clears, new operator stored
6 Press 2 2 Display shows 2
7 Press = 24 Chained result is 24
8 Press / 0 Display clears
9 Press 0 0 Display shows 0
10 Press = "ERR" (no display of NaN) Divide-by-zero error popup shown

If all ten steps pass, the calculator is operational. Tag the result in Calc_LastKey for diagnostic capture, and enable a periodic log to a CSV file on the panel if your image supports the file-system API.

Troubleshooting Matrix

Symptom on MP 370 Likely root cause Correction
Button press does nothing Script not compiled into the project Rebuild and re-transfer the project
Script runs only on first press Project function defined inside a screen script instead of project functions Move the routine to Scripts > Project Functions
Display shows "NaN" Result overflowed IEEE-754 double (e.g., 1e308 * 10) Cap operand ranges; add NaN guard
Calculation wrong after a few operations Operator not reset between operations Verify Calc_Operator reset in Calc_Compute
Decimal separator wrong on display Panel locale uses comma, project uses dot Match the decimal separator to Project > Language & Font
Runtime stops with "Script Error 0x800A000D" Type mismatch — string fed to CDbl Add IsNumeric check before CDbl
Transfer fails with "Version mismatch" WinCC Flexible build newer than RT image Match ES and RT versions, or rebuild RT image with ProSave
Display lags by 1–2 s Cyclical script consuming CPU Remove cyclical trigger; use pure event-driven model

Performance and Memory Notes

The MP 370's interpreter is roughly an order of magnitude slower than the engineering PC. A single Calc_Compute call that completes in under 1 ms on the PC typically takes 5–15 ms on the panel. Keep scripts short and avoid string concatenation in tight loops. The calculator above triggers only on button presses, so it adds no perceptible load to the runtime.

If you later expand the calculator with scientific functions (sin, cos, log, square root), add them as separate operator codes in the Select Case block. The single-operand functions such as sqrt can reuse Calc_OperandB as input and skip the dual-operand evaluation branch.

Alternate Approaches

If VBScript performance becomes a concern, or if the same calculator must run on multiple panel families (MP 277, MP 377, Comfort Panels), consider:

  • PLC-side calculation: implement the calculator in the PLC and read back the result via a single HMI tag. This removes script load from the panel entirely.
  • WinCC (TIA Portal) scripting: newer Comfort Panels use TIA Portal WinCC with the same VBScript model, plus a C-script option. Migrating to TIA Portal gives access to longer-term support.
  • Custom ActiveX control: registered on the panel image, exposes a calculator OCX. Only viable if ProSave is used to re-image the panel.

For a maintenance-friendly deployment on WinCC Flexible 2007 and MP 370, the VBScript project-functions approach documented above is the recommended path.

Field-Proven Caveats

  • The MP 370 resistive touch requires a calibrated pen or fingertip. Test the small numeric keys with a glove if the operator wears one.
  • Backlight lifetime on the 12" MP 370 is rated for 50,000 hours typical. Dimming the backlight during non-use extends lifetime.
  • Always commit the project to a backup folder after successful transfer. The MP 370 will not store revision history.
  • If the runtime is stopped via the Control Panel, Calc_Display retains its last value in non-volatile memory only if the tag is configured as retentive. By default, internal tags are volatile.

FAQ

Does WinCC Flexible 2007 on the MP 370 support VBScript natively?

Yes. WinCC Flexible 2007 Runtime includes the VBScript 5.6 engine and exposes the SmartTags, ShowSystemAlarm, and standard VBScript built-ins. No external runtime DLLs are needed on the panel.

Can I copy the calculator from one project to another?

Yes. Export the screen, the project functions, and the internal tags as a WinCC Flexible library, then import them into the target project. Verify tag names do not collide and that all events still bind to the correct buttons after import.

What happens if the operator enters more digits than the display can show?

The display tag is configured for 32 characters. If the operator exceeds it, the string is truncated silently. Add an explicit length check in the numeric-button scripts to ignore the press and trigger a short beep if you want the operator to see a limit hit.

Why does the equals button sometimes give a stale result after the panel restarts?

Internal tags are volatile by default. After a runtime restart, Calc_OperandA reverts to its configured initial value (0.0). Configure the operand and result tags as retentive under HMI Tags > Properties > Persistence if you need them to survive a warm restart.

Can the calculator run while the PLC connection is down?

Yes. The calculator uses only internal tags and does not depend on any PLC connection. It will operate fully during a PLC fault or communication break, which is useful for an operator entering a recipe value by hand.

Back to blog