/// <summary>
/// 获取串口称数据
/// </summary>
/// <returns></returns>
public static string GetWeight()
{
string weight = "";
SerialPort myPort = new SerialPort();
myPort.PortName = "COM2";//端口名
myPort.BaudRate = 2400; //波特率
myPort.DataBits = 8;//数据位
myPort.StopBits = StopBits.One; //停止位
myPort.Parity = Parity.None;//奇偶校验
myPort.RtsEnable = true;// 打开RTS ,这步很重要
try
{
myPort.Open(); // 打开端口
}
catch (Exception err)
{
MessageBoxEx.Show("打开COM口失败", UserHelper.GetUserConfig(UserConfig.title), MessageBoxButtons.OK, MessageBoxIcon.Information);//端口打开失败,返回
return "";
}
string[] Data = new string[10];
try
{
for (int i = 0; i < 5; i++)
{
Data[i] = myPort.ReadLine();
}
}
catch (Exception ex)
{
throw new CustomException(ex.Message, ExceptionType.Warn);
}
int isWT = 0;//稳定状态下获取重量的次数
for (int i = 0; i < 5; i++)
{
if (Data[0].Equals(Data[i]))
{
isWT++;
}
}
if (isWT >= 4)
{
Data[0] = Data[0].Substring(5).Trim();
weight = Data[0].Substring(0, Data[0].Length - 1).Trim();
}
myPort.Close();
return weight;
}