Modbus4.Core读取数据时的注意事项

        public override void Run(TaskContext context)
        {
            var serialPort1 = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
            try
            {
                context.WriteLog($"开始执行");
                serialPort1.ReadTimeout = 10 * 1000;
                serialPort1.Open();

                IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(serialPort1);
                byte slaveId = 1;//当前设备的地址为1
                var returnData = master.ReadHoldingRegisters(slaveId, 0, 2);


                var temoperatureValue = returnData[0] / (double)10;
                var humidityValue = returnData[1] / (double)10;

                context.WriteLog($"value:" + temoperatureValue + "|" + humidityValue);
            }
            catch (Exception ex)
            {
                context.WriteLog($"er:" + ex.Message + "|" + ex.StackTrace);
            }
            finally
            {
                serialPort1.Close();
            }
            context.WriteLog($"当前时是:{DateTime.Now}");
        }
    }
serialPort1.ReadTimeout = 10 * 1000;
如果不设置这个超时,就会一直等待,影响后面的运行。
posted @ 2020-08-06 16:04  星星c#  阅读(834)  评论(0编辑  收藏  举报