串口通信库
public class ComUtility
{
SerialPort serialPort;
private event DataReceivedHandle DataReceivedEvent;
public delegate void DataReceivedHandle(string data);
/// 串口接收通信配置方法
/// 端口名称
public ComUtility(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
{
serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceived);//DataReceived事件委托
serialPort.ReceivedBytesThreshold = 1;
serialPort.RtsEnable = true;
}
public void BindReceiveHandle(DataReceivedHandle handle)
{
DataReceivedEvent += handle;
}
/// 数据接收事件
private void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Thread.Sleep(2000);
byte[] readBuffer = new byte[serialPort.ReadBufferSize];
serialPort.Read(readBuffer, 0, readBuffer.Length);
string str = Encoding.Default.GetString(readBuffer).TrimEnd(' ');
DataReceivedEvent?.Invoke(str);
}
//打开串口的方法
public void OpenPort()
{
try//这里写成异常处理的形式以免串口打不开程序崩溃
{
serialPort.Open();
}
catch (Exception e)
{
throw e;
}
}
public void Close()
{
serialPort.Close();
}
//向串口发送数据
public void SendCommand(string CommandString)
{
byte[] WriteBuffer = Encoding.ASCII.GetBytes(CommandString);
serialPort.Write(WriteBuffer, 0, WriteBuffer.Length);
}
}
模拟调试需要用到两个工具
vspd串口模拟程序
串口调试小助手
先在vspt中添加模拟串口
随后可以在串口调试小助手中模拟发送
工具下载地址
https://files.cnblogs.com/files/ives/串口调试小助手.zip
https://files.cnblogs.com/files/ives/vspd串口模拟程序.zip