Skip to content
FalcoGoodbody edited this page Sep 10, 2020 · 14 revisions

Value conversion between C# and S7 plc

  • Read S7 Word:
ushort result = (ushort)plc.Read("DB1.DBW0");
  • Write S7 Word:
ushort val = 40000;
plc.Write("DB1.DBW0", val);
  • Read S7 Int / Dec, you need to use the method ConvertToShort():
short result = ((ushort)plc.Read("DB1.DBW0")).ConvertToShort();
  • Write S7 Int / Dec, you need to use the method ConvertToUshort():
short value = -100;
plc.Write("DB1.DBW0", value.ConvertToUshort());
  • Read S7 DWord:
uint result = (uint)plc.Read("DB1.DBD40");
  • Write S7 DWord:
uint val = 1000;
plc.Write("DB1.DBD40", val);
  • Read S7 DInt, you need to use ConvertToInt():
int result2 = ((uint)plc.Read("DB1.DBD60")).ConvertToInt();
  • Write S7 DInt:
int value = -60000;
plc.Write("DB1.DBD60", value);
  • Read S7 Real, you need to use ConvertToFloat():
float result = ((uint)plc.Read("DB1.DBD40")).ConvertToFloat();
  • Write S7 Real, you need to use ConvertToUInt():
float val = (float)35.687;
plc.Write("DB1.DBD40", val.ConvertToUInt());
  • Read S7 String
// reads a string from DataBlock 156 at address 0 with a length of 50 characters
var tempString = plc.Read(DataType.DataBlock, 156, 0, VarType.StringEx, 50, 0);      
myString = tempString.ToString();
  • Write S7 String, you should convert into a bytearray first
// helper function to convert String into ByteArray
private byte[] ConvertStringToByteArray(string myString)
        {
            // convert myString into ByteArray
            // for S7-String-Format:
            // 1. Byte = maximum length of the String
            // 2. Byte = actual length of the String         
   
            int maximumLength = 50; // <-- according to the length of your S7-String, here STRING[50]
            int actualLength = myString.Length;
            byte[] string = System.Text.Encoding.Default.GetBytes(myString);
            byte[] bytearray = new byte[actualLength + 2];

            bytearray[0] = Convert.ToByte(maximumLength);
            bytearray[1] = Convert.ToByte(actualLenght);

            // copy string-array into bytearray, begin at 3. byte 
            for (int i = 2; i < bytearray.Length; i++)
            {
                bytearray[i] = string[i - 2];
            }

            return bytearray;
        }

// use the helper function to convert myString into S7-String and write it to the plc
// write the string into DataBlock 204, startAddress 0
byte[] byteArray = ConvertStringToByteArray(myString);
plc.WriteBytes(DataType.DataBlock, 204, 0, byteArray);
  • Read Bool/Bit from byte
// reads 1 byte from DataBlock 153 at address 0
myByte = plc.ReadBytes(DataType.DataBlock, 153, 0, 1); // myByte = 5 = 0000 0101
myByte.SelectBit(0)  // true
myByte.SelectBit(1)  // false
  • Write bool/bit from byte
// writes FALSE to DataBlock 157, startAddress 0, bitAddress 0
plc.WriteBit(DataType.DataBlock, 157, 0, 0, false);
Clone this wiki locally