c# 使用Sharp7对PLC读写操作

static S7Client client = new S7Client();
        static void Main(string[] args)
        {
            var res = client.ConnectTo("192.168.1.1", 0, 1);//连接PLC的IP地址
            if (res == 0)
            {
                while (true)
                {
                    byte[] db3Buffer = new byte[4];
                    var result = client.DBRead(127, 178, db3Buffer.Length, db3Buffer);//读取DB127.DBD178位置数据到db3Buffer当中
                    if (result == 0)//判断操作成功标识,成功0,否则不成功
                    {
                        double db3dbd4 = S7.GetRealAt(db3Buffer, 0);//将获取的数据进行转换成Real类型,需要确定PLC当中此数据为Real类型方可
                        Console.WriteLine("DB127.DBD178: " + db3dbd4);
                    }


                    db3Buffer = new byte[4];

                    db3Buffer.SetRealAt(0, 345f);//将 345 数据存入buffer当中后续写入到PLC
                    //此方法为扩展方法,也可以写成
                    //S7.SetRealAt(db3Buffer, 0, 345);
                    result = client.DBWrite(127, 54, db3Buffer.Length, db3Buffer);//将buffer数据写入PLC位置DB127.DBD54,类型为Real
                    if (result != 0)
                    {
                        Console.WriteLine("Error: " + client.ErrorText(result));
                    }

                    Thread.Sleep(1000);
                }
            }
            Console.ReadKey();
        }

 

posted @ 2021-04-13 09:33  my_paradise  阅读(2820)  评论(0编辑  收藏  举报