C#:
SerialPort _serialPort = new SerialPort("COM1", 4800, Parity.Even, 8, StopBits.One);
byte[] vals = {0x01, 0x01, 0x00, 0x00, 0x00, 0x08, 0x3d, 0xcc};
byte[] recv_vals;
int recv_bytes;
int temp_int;
bool packet_received = false;
_serialPort.Open();
_serialPort.Write(vals,0, vals.Length);
_serialPort.ReadTimeout = 1000; // 1 second response timeout
recv_vals = new byte[256]; // maximum Modbus RTU packet is 256 bytes
recv_bytes = 0;
try
{
temp_int = _serialPort.ReadByte();
// calculate 3.5 character times in ms = 1000ms in 1 second, 1 start bit, 8 data bits, 1 parity bit, 1 stop bit, divide by baud rate of 4800 and multiply by 3.5
_serialPort.ReadTimeout = (int)((3.5 * (1000 * (1 + 8 + 1 + 1))) / 4800);
_serialPort.ReadTimeout++; // round up by 1, also accounts for cases where calculated timeout is 0
while (temp_int >= 0)
{
recv_vals[recv_bytes] = (byte)temp_int;
recv_bytes++;
temp_int = _serialPort.ReadByte();
}
}
catch (TimeoutException)
{
if (recv_bytes > 0)
packet_received = true;
}
if (packet_received)
{
Console.WriteLine("Received {0} bytes", recv_bytes);
for (int i = 0; i < recv_bytes; i++)
Console.Write("{0:X2} ", recv_vals[i]);
}
else
{
Console.WriteLine("Request Timed Out");
}
_serialPort.Close();