I'm very new to sending data over a serial port through .net and I've noticed after implementing a TCP counterpart that I wouldn't get it that easy with serial!
So to start at the top, I am nearly there with my serial bi-directional communication implementation I am just getting stuck on a few things: -
- My reads are being split across multiple messages or received as a fragmented response over the COM port and I don't know what settings I might need, or how I should write the code differently to fix this. What could cause this? I am inspecting the message at a breakpoint on
SerialPort_DataReceived.
Basically the data should be sent as:
01: LS|DA090521|TI111043|q
02: PS|RN102|PTC|TA1040000|P#0|DA090521|TI111429|j
but it is being split (at random positions on each requested read)
01: LS|DA090521|TI111
02: 043|q
03: PS|RN102|PTC|TA1
04: 0000|P#0|DA090521|TI111429|j
- Question 1 has been answered, thanks Chris W. and others! I now have the message I expect being built from fragments progressively (looking out for STX, {msg body}, ETX) and then an action performed when message has been completely built, and got it going with a thread-safe Queue, very happy.
. 2. I am receiving a "|" symbol through my read nearly every cycle, is this due to a command I have set wrongly somehow, an artifact of Serial communication, or something the device is sending me? (I don't think so though, as Hyperterminal connectivity reveals this character is not being sent continuously.)
. 3. Can you confirm I am reading and writing data correctly in the respective methods.
Thanks guys for looking at my other two questions too.
Relevant code as follows:
...
// COM3, 9600, None, 8, One
SerialPort = new SerialPort(comPort, baudRate, parity, dataBits, stopBits);
if (SerialPort.IsOpen) SerialPort.Close();
// SerialPort.RtsEnable = true; // Request-to-send
// SerialPort.DtrEnable = true; // Data-terminal-ready
SerialPort.ReadTimeout = 150; // tried this, but didn't help
SerialPort.WriteTimeout = 150; // tried this, but didn't help
SerialPort.Open();
SerialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
}
void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Process received data
SerialPort sp = (SerialPort)sender;
byte[] buffer = new byte[sp.BytesToRead];
int bytesRead = sp.Read(buffer, 0, buffer.Length);
// message has successfully been received
message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
}
public bool SendMessage(string text)
{
// Only send message if a client is connected
if (SerialPort != null && SerialPort.IsOpen)
{
byte[] buffer = Encoding.ASCII.GetBytes(text);
SerialPort.Write(buffer, 0, buffer.Length);
}
}