Menu
CoddyTech

REAL Math

Part of the Structured Text section of Coddy's PLC Programming journey. Lesson 14 of 17.

In section 5 you moved the raw level into a DINT, then scaled it with MUL and DIV, so the numbers would not overflow. A REAL holds fractions and very large numbers, so scaling becomes one line:

VAR
    Pct : REAL;
END_VAR

Pct := INT_TO_REAL(Level) * 100.0 / 32767.0;

INT_TO_REAL turns the INT into a REAL first, so the whole calculation is done in REAL. Write REAL numbers with a point: 100.0. Newer editors such as CODESYS also accept the short form TO_REAL(Level).

Without the conversion, Level * 100 is an INT by the IEC rules: it is too big, so here and in Siemens SCL it wraps around to a wrong number. CODESYS and TwinCAT happen to calculate it in 32 bits, but do not count on it: convert first.

REAL_TO_INT goes back: it rounds to the nearest whole number, so 59.6 becomes 60.

challenge icon

Challenge

Medium
  • Declare Pct as a REAL and compute the level in percent from Level.
  • Fill while Pct is below 60.0, so the tank fills to 60 % and stays there.

Press Run, try it on the machine, then Check.

Try it yourself

VAR
    // declare Pct here
END_VAR

// The level in percent

// Fill below 60 %
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Structured Text

Practice on your own: PLC playground