Read/Write PLC tags folder from PLC using c#

674 Views Asked by At

I'm developing a C# application and I need to read/write values from PLC tags folder (TIA Portal). I have looked at S7.Net library and Libnodave but they only read/write data blocks and not tags like my project.

What it proposes :

bool val = true;
plc.Write("DB1.DBX0.0", val);

What I'm willing to get :

bool val = true;
plc.Write("I0.0", val);

Do you have any idea of doing it ? PS: I know there is a old post like this but not resolved.

1

There are 1 best solutions below

3
Артем Павлов On

I'd recomend to use Sharp7, it is a C# port of Snap7 library. To read/write input bytes you can use EBRead/EBWrite functions or if you want to read/write bit use ReadArea/WriteArea functions Sharp7 wiki. Also check target compability for your plc model.

For example to read plc input code can look like this:

    static void Main(string[] args)
    {
        var client = new S7Client();
        //I connect to PLCSIM via NetToPLCSim
        int result = client.ConnectTo("127.0.0.1", 0, 2);
        if (result != 0)
        {
            //If value result of operation != 0 shows error
            Console.WriteLine(client.ErrorText(result));
        }
        else
        {
            //Buffer it is a byte array of some size, that you use to read data from plc or to write to it
            //This buffer size is 1 byte, bc i need only one bit and EBRead can't read less than 1 byte
            var buffer = new byte[1];
            //First parameter is offset, i.e. if you read 1 byte from offset 0 you read whole IB0
            //Second parameter define how many bytes you will read in buffer, make it equal to your buffer size
            //Third parameter is buffer in which the data is written when you perform read operation
            result = client.EBRead(0, buffer.Length, buffer);
            if (result != 0)
            {
                Console.WriteLine(client.ErrorText(result));
            }
            else
            {
                //Here you convert data from buffer to desiered c# type
                //First parameter is buffer with data
                //Second parameter is byte offset in buffer 
                byte input = S7.GetByteAt(buffer, 0);
                //Third parameter is only to get bit operation, to specify bit number in byte
                bool I0_0 = S7.GetBitAt(buffer, 0, 0);
                Console.WriteLine(I0_0);
            }
        }
        Console.ReadKey();
    }

NetToPLCSim