C# 每个字节接受 处理串口数据 的方法
/// <summary>
/// 向串口发送信息,有返回值
/// </summary>
/// <param name="serialPort"></param>
/// <param name="strMsg"></param>
/// <returns></returns>
private string QueryPortMsg(System.IO.Ports.SerialPort serial, string strMsg)
{
string MsgBuf = "";
try
{
SendPortMsg(serial, strMsg);
int rcv;
MsgBuf = "";
while (true)
{
if (serial.BytesToRead > 0)
{
rcv = serial.ReadChar();
if (rcv == '\n')
{
break;
}
else
{
if (rcv == '\r')
{
}
else
{
MsgBuf += Convert.ToChar(rcv);
}
}
}
}
}
catch (Exception Ex)
{
}
return MsgBuf;
}
/// <summary>
/// 向串口发送信息,无返回值
/// </summary>
/// <param name="serialPort">需要发送的串口</param>
/// <param name="data">发送数据</param>
private void SendPortMsg(System.IO.Ports.SerialPort serialPort, string data)
{
try
{
data = data + "\r\n";
serialPort.WriteLine(data);
}
catch
{
}
}