【实例简介】
C#打开串口与电子秤监听电子秤上的读数
【实例截图】
【核心代码】
#region 成员
SerialPort serialPort;
int speed = 300;
/// 获取或设置电脑取COM数据缓冲时间,单位毫秒
public int Speed
{
get { return speed; }
set
{
if (value < 300)
throw new Exception("串口读取缓冲时间不能小于300毫秒!");
speed = value;
}
}
///
public string StartKey = "wm";
///
public string UnitKey = "kg";
///
public string MatchPattern = @"wn\w .\w kg";
WeightInformation weightInformation = new WeightInformation();
///
public WeightInformation WeightInformationObj
{
get { return weightInformation; }
}
/// 页变化时引发的事件
public event EventHandler Changed;
/// 引发Changed事件
protected void OnChanged()
{
if (Changed != null)
Changed(this, EventArgs.Empty);
}
#endregion 成员
#region 构造与析构
///
public void Dispose()
{
Close();
serialPort = null;
}
#endregion 构造与析构
/// 初始化串口
/// 数据传输端口
/// 波特率
/// 串口读数缓冲时间
///
public bool Open(string portName, int baudRate = 4800, int speed = 300, int readTimeout = 600, int writeTimeout = 1200)
{
Close();
try
{
serialPort = new SerialPort(portName, baudRate, Parity.None, 8);
serialPort.ReceivedBytesThreshold = 10;
serialPort.Handshake = Handshake.RequestToSend;
serialPort.ReadTimeout = readTimeout;
serialPort.WriteTimeout = writeTimeout;
this.Speed = speed;
if (!serialPort.IsOpen)
serialPort.Open();
serialPort.DataReceived = new SerialDataReceivedEventHandler(serialPort_DataReceived);
return true;
}
catch (Exception exp)
{
throw new Exception(string.Format("无法初始化串口{0}!", portName), exp);
}
}