嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 1 元微信扫码支付:1 元
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
C#打开串口与电子秤监听电子秤上的读数
#region 成员
SerialPort serialPort;
int speed = 300;
/// <summary>获取或设置电脑取COM数据缓冲时间,单位毫秒</summary>
public int Speed
{
get { return speed; }
set
{
if (value < 300)
throw new Exception("串口读取缓冲时间不能小于300毫秒!");
speed = value;
}
}
/// <summary></summary>
public string StartKey = "wm";
/// <summary></summary>
public string UnitKey = "kg";
/// <summary></summary>
public string MatchPattern = @"wn\w .\w kg";
WeightInformation weightInformation = new WeightInformation();
/// <summary></summary>
public WeightInformation WeightInformationObj
{
get { return weightInformation; }
}
/// <summary>页变化时引发的事件</summary>
public event EventHandler Changed;
/// <summary>引发Changed事件</summary>
protected void OnChanged()
{
if (Changed != null)
Changed(this, EventArgs.Empty);
}
#endregion 成员
#region 构造与析构
/// <summary></summary>
public void Dispose()
{
Close();
serialPort = null;
}
#endregion 构造与析构
/// <summary>初始化串口</summary>
/// <param name="portName">数据传输端口</param>
/// <param name="baudRate">波特率</param>
/// <param name="speed">串口读数缓冲时间</param>
/// <returns></returns>
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);
}
}