资源预览内容
第1页 / 共5页
第2页 / 共5页
第3页 / 共5页
第4页 / 共5页
第5页 / 共5页
亲,该文档总共5页全部预览完了,如果喜欢就下载吧!
资源描述
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 Speedgetreturn this._speed;setif (value / 初始化串口/ / 数据传输端口/ 波特率/ 串口读数缓冲时间/ public bool InitCom(string PortName, int BaudRate,int Speed) trysp = 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 / 从字符串中取值/ / 起始字符串/ 间隔位长度/ 值长度/ 源字符串/ private string DecodeValue(string head, int intervalLen, int valueLen,string src)int index = src.IndexOf(head);return src.Substring(index + intervalLen, valueLen);/ / 取重量/ / 源字符串/ private string DecodeWeightData(string srcString)return this.DecodeValue(GS, 3, 8,srcString);/ / 取重量单位/ / 源字符串/ private string DecodeWeightUnit(string srcString)return this.DecodeValue(GS, 12, 2, srcString);/ / 取百分数/ / 源字符串/ private string DecodePercentage(string srcString)return this.DecodeValue(U.W., 4, 14, srcString);/ / 取数量/ / 源字符串/ private string DecodeQualityData(string srcString)return this.DecodeValue(PCS, 3, 9, srcString); / / 取数量单位/ / 源字符串/ private string DecodeQualityUnit(string srcString)return this.DecodeValue(PCS, 12, 3, srcString); #endregion#region 释放所有资源public void Dispose()if (sp != null & sp.IsOpen)sp.Close();#endregion
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号