C#实现串口中继
前一段时间为了测试硬件产品,发现,串口转发不太方便,于是自己写了一个简单的串口中继小程序,是基于C#开发的,可以将两个串口互通,方便自己在程序的使用,目前看起来应用还可以,现在把源码放这里,供大家参考。
串口使用的是C#提供的控件,直接拖动的控件,实现了相关的事件,界面如图:
核心代码也很简单
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(200);
byte[] byteRead = new byte[serialPort1.BytesToRead];
serialPort1.Read(byteRead, 0, byteRead.Length);
setText1( "接收数据:" + ToHexStrFromByte(byteRead));
if (serialPort2.IsOpen == true)
{
serialPort2.Write(byteRead, 0, byteRead.Length);
setText2( "发送数据:" + ToHexStrFromByte(byteRead));
}
}
private void serialPort2_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(200);
byte[] byteRead = new byte[serialPort2.BytesToRead];
serialPort2.Read(byteRead, 0, byteRead.Length);
setText2( "接收数据:" + ToHexStrFromByte(byteRead));
if (serialPort1.IsOpen == true)
{
serialPort1.Write(byteRead, 0, byteRead.Length);
setText1("发送数据:" + ToHexStrFromByte(byteRead));
}
}
为了打印使用的一个小函数:
/// <summary>
/// 字节数组转16进制字符串:空格分隔
/// </summary>
/// <param name="byteDatas"></param>
/// <returns></returns>
public string ToHexStrFromByte(byte[] byteDatas)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < byteDatas.Length; i++)
{
builder.Append(string.Format("{0:X2} ", byteDatas[i]));
}
return builder.ToString().Trim();
}