How to read data from serial port and write to serial port?
Solution 1
Just to give you an idea this is a very simple function that writes a command as a byte
array on a serial and reads corresponding input from serial port (in this example I read only the fourth byte of the value read from the serial port):
private string ReadFromSerial()
{
try
{
System.IO.Ports.SerialPort Serial1 = new System.IO.Ports.SerialPort("COM1", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
Serial1.DtrEnable = true;
Serial1.RtsEnable = true;
Serial1.ReadTimeout = 3000;
var MessageBufferRequest = new byte[8] { 1, 3, 0, 28, 0, 1, 69, 204 };
var MessageBufferReply = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
int BufferLength = 8;
if (!Serial1.IsOpen)
{
Serial1.Open();
}
try
{
Serial1.Write(MessageBufferRequest, 0, BufferLength);
}
catch (Exception ex)
{
logEx(ex);
return "";
}
System.Threading.Thread.Sleep(100);
Serial1.Read(MessageBufferReply, 0, 7);
return MessageBufferReply[3].ToString();
}
catch (Exception ex)
{
logEx(ex);
return "";
}
}
Solution 2
Here is a link to the MSDN documentation that you should find really helpful: the documentation. There are some properties for what you are looking for and some good examples.
user2628363
Updated on June 04, 2022Comments
-
user2628363 almost 2 years
Hi I'm writing an application in c# to connect to a device via rs232(com) port. I need to send a "read" command to read data from it and a "write" command to send some data to it.
I read some articles in here and some other sites and I know there are some methods when I'm defining a serial port in c#.
but my question is ,should I be concerned about DTR ,RTS ,... ? what are they for? How do I use them?
-
CodeCaster almost 11 years
-
-
user2628363 almost 11 yearsvery informative thanks. Another question: If I want to read several times ,'Serial1.IsOpen' should be the condition for the loop or something else?
-
Andrea almost 11 years@user2628363 Yes, you can create a loop
While(Serial1.IsOpen)
that keeps on writing/reading on the port. -
user2628363 almost 11 yearsthanks and what are dtr and rts for?
-
Andrea almost 11 years@user2628363 They're for hardware flow control; for correct usage you should check the documentation of the device you want to communicate with