public ModbusRequestCreator() { ModbusRTUMaster master = new ModbusRTUMaster(); master.SlaveAddr = SetAddress(1); master.StartReg = SetStartRegister(0); master.RegCount = SetRegistersCount(1); Console.WriteLine($"Choose modbus function(default - 0x03):"); Console.WriteLine("1. Read holding reg - 0x03"); Console.WriteLine("2. Write holding reg - 0x10"); var key = Console.ReadKey().Key; if (key == ConsoleKey.NumPad2 || key == ConsoleKey.D2) { master.FuncCode = 0x10; var msg = SetMessage(); var payload = CreateDataPayload(msg); var request = master.CreateMessage(payload).ToArray(); Program.MySerialPort.serialPort.Write(request, 0, request.Length); } else { master.FuncCode = 0x03; var request = master.CreateMessage().ToArray(); Program.MySerialPort.serialPort.Write(request, 0, request.Length); } //var byteRequest = master.CreateMessage(); //var stringRequest = CreateModbusRTUDataString(master); //Program.MySerialPort.serialPort.WriteLine(stringRequest); Console.Read(); }
public string CreateModbusRTUDataString(ModbusRTUMaster p_Msg) { string RetVal = ""; for (int i = 0; i < p_Msg.MsgSize; i++) { RetVal += ("0x" + p_Msg.Msg[i].ToString("X2") + " "); } return(RetVal); }