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 }