SerialPort访问接口获取电子称数据

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

using System;

using System.IO.Ports;

using System.Text;

using System.Threading;

///

/// 封装COM口数据

///

public class ComInformation

{

string _wdata;

string _wunit;

string _qdata;

string _qunit;

string _percentage;

///

/// 获取或设置重量

///

public string WData { get { return this._wdata; } set { this._wdata = value; } }

///

/// 获取或设置重量单位

///

public string WUnit { get { return this._wunit; } set { this._wunit = value; } }

///

/// 获取或设置数量

///

public string QData { get { return this._qdata; } set { this._qdata = value; } }

///

/// 获取或设置数量单位

///

public string QUnit { get { return this._qunit; } set { this._qunit = value; } }

///

/// 获取或设置百分数

///

public string Percentage { get { return this._percentage; } set { this._percentage =

value; }}

}

///

/// 电子称数据读取类

///

public class WeightReader : IDisposable

#region 字段、属性与构造函数

SerialPort sp;

int _speed = 300;

///

/// 获取或设置电脑取COM数据缓冲时间,单位毫秒

///

public int Speed

{

get

{

return this._speed;

}

set

{

if (value < 300)

throw new Exception("串口读取缓冲时间不能小于300毫秒!");

this._speed = value;

}

}

public bool InitCom(string PortName)

{

return this.InitCom(PortName, 4800, 300);

}

///

/// 初始化串口

///

/// 数据传输端口

/// 波特率

/// 串口读数缓冲时间

///

public bool InitCom(string PortName, int BaudRate,int Speed)

{

try

{

sp = new SerialPort(PortName, BaudRate, Parity.None, 8);

sp.ReceivedBytesThreshold = 10;

sp.Handshake = Handshake.RequestToSend;

sp.Parity = Parity.None;

sp.ReadTimeout = 600;

sp.WriteTimeout = 600;

this.Speed = Speed;

if (!sp.IsOpen)

{

sp.Open();

}

return true;

}

catch

{

throw new Exception(string.Format("无法初始化串口{0}!",PortName));

}

}

#endregion

#region 串口数据读取方法

public WeightInformation ReadInfo()

{

string src = this.ReadCom();

WeightInformation info = new WeightInformation();

info.WData = this.DecodeWeightData(src);

info.WUnit = this.DecodeWeightUnit(src);

info.Percentage = this.DecodePercentage(src);

info.QData = this.DecodeQualityData(src);

info.QUnit = this.DecodeQualityUnit(src);

return info;

}

///

/// 将COM口缓存数据全部读取

///

///

private string ReadCom()//返回信息

{

if (this.sp.IsOpen)

{

Thread.Sleep(this._speed);

string res = "";

//for (int i = 0; i < 5; i++)

//{

byte[] buffer = new byte[sp.BytesToRead];

sp.Read(buffer, 0, buffer.Length);

res = System.Text.Encoding.ASCII.GetString(buffer);

//if (res != "")

// break;

//}

if (res == "")

{

throw new Exception("串口读取数据为空,参数设置是否正确!");

}

return res;

}

return "";

}

#endregion

相关文档
最新文档