Read string from plc using moka7

2.3k views Asked by At

How to read string from PLC from DB560 with offset 0.0 and size 12 bytes. Garbage value is coming at the output.

S7Client client = new S7Client();
client.SetConnectionType (S7.S7_BASIC);
int res = client.ConnectTo("192.168.0.1", 0, 1); 
byte[] data = new byte[12];
client.ReadArea(S7.S7AreaDB, 560, 0, 12, data); 
String ret = S7.GetStringAt(data,0,12);
System.out.println(ret);
1

There are 1 answers

0
dergroncki On

The first 2 bytes of the S7 data type string are as follows:

Positon n: Maximum length
Postion n+1: Current length

Because of this the first character is not at position n but at positon n+2.

byte[] data = new byte[14];
client.ReadArea(S7.S7AreaDB, 560, 0, 14, data);
String ret = S7.GetStringAt(data,0+2,12);

Alternative:

byte[] data = new byte[12];
client.ReadArea(S7.S7AreaDB, 560, 2, 12, data);
String ret = S7.GetStringAt(data,0,12);

Or you change the moka7 code to something like this (this is the code of sharp7):

public static string GetStringAt(byte[] Buffer, int Pos)
{
    int size = (int)Buffer[Pos + 1]; //Current length of the string
    return Encoding.UTF8.GetString(Buffer, Pos + 2, size);
}