1. 程式人生 > 實用技巧 >Modbus4.Core讀取資料時的注意事項

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;
如果不設定這個超時,就會一直等待,影響後面的執行。