【C#使用S7.NET库读取和写入西门子PLC变量】

C#使用S7.NET库读取和写入西门子PLC变量

  • 前言
  • 使用S7.NET库读取
  • 使用S7.NET库写入

前言

本来想用Wincc的接口给读和写Wincc,但是速度实在太感人了,所以不如直接读和写PLC的变量,这种方式速度瞬间快了不知道多少倍(经测试4000个变量几乎瞬间完成,应该1s左右,人感知不出来)。

网上找了好多资料,都写得比较分散。特别是关于字符串的读取和写入,写了好久才读写正常,把两种方式的代码分享出来。

使用S7.NET库读取

        //使用S7.NET库___读取PLC变量
        public static string[] ReadPLC(int DbAddress,int StartByteAdr,int ByteCount,int Type)
        {
   
            int i, j, k;
            int types = 2;
            int count;
            byte[] bytes=new byte[1000];
            //返回值当前设置最大1000,可自由设置
            string[] result=new string[1000];

            #region plc系列号+机架号+插槽号
            Plc MyPLC = new Plc(CpuType.S71500, "10.168.4.2", 0, 1);
            MyPLC.Open();
            #endregion

            //读取的是int
            if (Type == 1)
            {
   
                types = 2;
            }
            //读取的是real
            else if (Type == 2)
            {
   
                types = 4;
            }
            //读取的是String
            else if (Type == 3)
            {
   
                types = 256;
            }
            //读取的是bool
            else if(Type == 0)
            {
   
                types = 1;
            }

            try
            {
   
                j = 0;
                if (types == 1)
                {
   
                    //读取BOOL
                    for (i = 0; i < Convert.ToInt16(ByteCount / 8 + 1); i++)
                    {
   
                        for (k = 0; k <= 7; k++)
                        {
   
          

你可能感兴趣的:(C#,c#,.net,java)