Пример #1
0
        /// <summary>
        /// 设置PLC中ModbusTCP HoldReg DB块 第index个数的大小,可以是任意类型
        /// </summary>
        public bool SetVal(int index, float val, ModbusTCPMaster MBmaster)
        {
            byte[] bytes;
            switch (TypeList[index])
            {
            case "System.Byte":
                var data1 = (byte)val;
                bytes = new byte[] { data1 };
                break;

            case "System.Int16":
                var data2 = (Int16)val;
                bytes = BitConverterHelper.Int16ToBytes(data2);
                break;

            case "System.Int32":
                var data3 = (Int32)val;
                bytes = BitConverterHelper.Int32ToBytes(data3);
                break;

            case "System.Single":
                var data4 = (Single)val;
                bytes = BitConverterHelper.SingleToBytes(data4);
                break;

            default: throw new Exception("Type is not correct!");
            }
            ushort address = (ushort)(getDataOffset(index) / 2);

            MBmaster?.WriteMultipleRegister(ModbusTCPMaster.WriteMultipleRegisterFucID, SlaveID, address, bytes);
            Thread.Sleep(20);
            return(true);
        }
Пример #2
0
        public bool SetVals(int startindex, float[] vals, ModbusTCPMaster MBmaster)
        {
            byte[] bytes;
            byte[] returnbytes = { };
            int    count       = vals.Length;

            for (int i = 0; i < count; ++i)
            {
                switch (TypeList[startindex + i])
                {
                case "System.Byte":
                    var data1 = (byte)vals[i];
                    bytes = new byte[] { data1 };
                    break;

                case "System.Int16":
                    var data2 = (Int16)vals[i];
                    bytes = BitConverterHelper.Int16ToBytes(data2);
                    break;

                case "System.Int32":
                    var data3 = (Int32)vals[i];
                    bytes = BitConverterHelper.Int32ToBytes(data3);
                    break;

                case "System.Single":
                    var data4 = (Single)vals[i];
                    bytes = BitConverterHelper.SingleToBytes(data4);
                    break;

                default: throw new Exception("Type is not correct!");
                }
                returnbytes = BitConverterHelper.BytesConnect(returnbytes, bytes);
            }

            ushort address = (ushort)(getDataOffset(startindex) / 2);

            MBmaster?.WriteMultipleRegister(ModbusTCPMaster.WriteMultipleRegisterFucID, SlaveID, address, returnbytes);
            Thread.Sleep(20);
            return(true);
        }