Converting real data type from Siemens PLC (S7-1200) to be displayed in Visual C# Windows Form

9.3k views Asked by At

I am trying to read a real value from a Siemens PLC (S7-1200) and display it in Windows Form. I am using the S7.NET library to communicate with the PLC and a TIA Portal V15 to program/Monitor the PLC.

I am able to read the particular data block (DB3.DBD0) in the Windows Form from the PLC, it does return a value, but the value is displayed in some other format. For example, if I modify the value in DB3.DBD0 to "2.22", it gives me "1.074665+09". I would like it to return the same value as in the TIA Portal which is "2.22".

Below is the code I am using to convert the values.

object real0 = Convert.ToSingle(plc.Read("DB3.DBD0"));
label43.Text = real0.ToString();

If my question is not clear, please let me know, I can try to explain in more detail.

Thank you in advance!

3

There are 3 answers

0
Shep On

The PLC data type appears to be a REAL (Floating-point number) 'IEEE Floating-point number' as per http://www.plcdev.com/step_7_elementary_data_types

These numbers are represented as fractions, whereby 2.2 cannot be accurately defined. Great detailed explanation: Why are floating point numbers inaccurate?

Good simple explanation: https://floating-point-gui.de/basic

Try converting to decimal data types, then rounding to remove trailing 0's

0
Mehmet Erdoğmuş On

Siemens and other PLC systems store those numbers as WORDs.

For example 2.22 floating point/real value is stored as 0x400E147B in PLC. in ABCD byte order. A=40, B=0E, C=14, D=7B.

But as I can see you are reading correct hexadecimal value from PLC but converting it as 32bit INTEGER.

You can check from: https://www.scadacore.com/tools/programming-calculators/online-hex-converter/

0
Victor Pieper On

You have to cast it as an uint and convert it to a double.

for example: var real0 = Convert.ToDouble((uint)plc.Read("DB3.DBD0")); or this: var real0 = ((uint)plc.Read("DB3.DBD0")).ConvertToDouble();

I hope this helped :)

for more examples you can try this video, it is a bit outdated so you might need to do some small things different: https://www.mesta-automation.com/siemens-s7-plc-c-s7-net-plc-driver/