標籤:des style blog color io os ar 使用 for
2012年時即做過一個地磅稱重軟體,最近公司又接了一個地磅過磅軟體的項目,把遇到的問題總結一下以備後用。
1.接線問題
因為客戶方原來單獨使用儀錶,儀錶未有接線和電腦串連,為此頗費周折才做好了接線。接線方式為儀錶端所接陣腳為7、8,電腦端為2、5
2.讀取儀錶稱重數
代碼基本沿襲2012年為另一客戶所開發的稱重軟體的代碼。
註:本次客戶所使用地磅為泰山衡器廠出的XK3200,但說明書上說明和耀華系列地磅相容,而上一客戶所使用地磅正是耀華XK3190,大概因此代碼基本可直接通用。
下面貼代碼了,使用的serialPort控制項,命名為port
稱重表單設計器字碼頁 FrmWeigh.designer.cs中
this.port.BaudRate = 2400;this.port.Parity = System.IO.Ports.Parity.Even;this.port.StopBits = System.IO.Ports.StopBits.OnePointFive;this.port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.port_DataReceived);
稱重表單FrmWeigh.cs擷取地磅儀錶數核心代碼部分:
1 /// <summary> 2 /// 串口讀取資料 3 /// </summary> 4 private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 5 { 6 Thread.Sleep(100); 7 if (false == this.port.IsOpen) return; 8 byte firstByte = Convert.ToByte(port.ReadByte()); 9 if (firstByte == 0x02)10 {11 int bytesRead = port.ReadBufferSize;12 byte[] bytesData = new byte[bytesRead];13 byte byteData;14 15 for (int i = 0; i < bytesRead - 1; i++)16 {17 byteData = Convert.ToByte(port.ReadByte());18 if (byteData == 0x03)//結束19 {20 break;21 }22 bytesData[i] = byteData;23 }24 strReceive = Encoding.Default.GetString(bytesData);25 }26 tbWeight.Invoke(new EventHandler(delegate { tbWeight.Text = GetWeightOfPort(strReceive); }));27 }28 29 /// <summary>30 /// 返回串口讀取的重量31 /// </summary>32 /// <param name="?"></param>33 /// <returns></returns>34 private string GetWeightOfPort(string weight)35 {36 if (string.IsNullOrEmpty(weight) || weight.IndexOf("+") < 0 || weight.Length < 6)37 {38 return "0.000";39 }40 weight = weight.Replace("+", "");41 weight = int.Parse(weight.Substring(0, 3)).ToString() + "." + weight.Substring(3, 3);42 return weight;43 }
c#開發地磅稱重軟體