通过串口对磅秤集成,实时读取磅秤数据
C#技术,串口通信
主要用到的是与串口的交互方法,以及通过反射的方式,让程序达到只用更新插件就能对各种磅秤进行集成
先来一张软件界面运行截图
1、打开串口
private void OpenCom()
{
try
{
if (SpCom.IsOpen)
{
SpCom.Close();
}
if (t == "7")
{
calss = getClass();
method = calss.GetType().GetMethod("GetData");
}
//else
//{
substrStart = Convert.ToInt32(tbStart.Text);
substrLen = Convert.ToInt32(tbLen.Text);
//"COM3"; //
SpCom.PortName = cbCK.Text;// comboBox1.SelectedItem.ToString();
SpCom.BaudRate = Convert.ToInt32(cbBT.Text);// 2400;
SpCom.Parity = (Parity)cbJO.SelectedIndex;// Parity.Even;
SpCom.DataBits = Convert.ToInt32(tbSJ.Text);
SpCom.StopBits = (StopBits)cbTZ.SelectedIndex;
//}
SpCom.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
// throw;
}
}
1、关闭串口
private void CloseCom()
{
if (SpCom.IsOpen)
{
SpCom.Close();
}
}
3、接收数据,数据处理部分,针对不规则的数据,用到第7种动态库解析方式
private void serialWeight_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (ReceiveData)
{
//richTextBox1.AppendText(t + "\r\n");
weight_weight_txt.Invoke(new EventHandler(delegate
{
try
{
string txt = string.Empty;
switch (t)
{
case "1":
txt = SpCom.ReadExisting();
richTextBox1.AppendText(txt + "\r\n");
txt = txt.Substring(substrStart, substrLen);
weight_weight_txt.Text = txt.Trim();
break;
case "2":
txt = SpCom.ReadLine();
richTextBox1.AppendText(txt + "\r\n");
txt = txt.Substring(substrStart, substrLen);
weight_weight_txt.Text = txt.Trim();
break;
case "3":
txt = SpCom.ReadExisting();
richTextBox1.AppendText(txt + "\r\n");
if (txt.Length == 8)
{
if (txt.Contains(' '))
{
w = txt.Split(' ')[1];
}
else
{
w += txt.Substring(0, 2);
}
if (w.Length == 6)
{
weight_weight_txt.Text = w;
w = string.Empty;
}
}
break;
case "4":
txt = SpCom.ReadExisting();
richTextBox1.AppendText(txt + "\r\n");
if (txt.Contains(")"))
{
w = txt.Substring(4, 4);
}
if (w != "" && !txt.Contains(")") && txt.Contains(" "))
{
w += txt.Substring(0, 2);
}
if (w.Length == 6 && !w.Contains(')'))
{
weight_weight_txt.Text = w.Replace(' ', '0');
w = string.Empty;
}
break;
case "5":
txt = SpCom.ReadExisting();
richTextBox1.AppendText(txt + "\r\n");
if (txt.Length > 6 && !txt.Contains(" "))
{
w = txt.Substring(4, 4);
}
if (txt.Length > 6 && txt.IndexOf(" ") == 2)
{
w += txt.Substring(0, 2);
}
if (w.Length == 6 && txt.IndexOf(" ") != 2 && txt.IndexOf(" ") != 3)
{
weight_weight_txt.Text = w.Replace(' ', '0');
w = string.Empty;
}
break;
case "6":
txt = SpCom.ReadExisting();
richTextBox1.AppendText(txt + "\r\n");
if (txt.Length > 6 && txt.IndexOf(" ") != 2)
{
w = txt.Substring(4, 4);
}
if (txt.Length > 6 && txt.IndexOf(" ") == 2)
{
w += txt.Substring(0, 2);
}
if (w.Length == 6 && txt.IndexOf(" ") != 2)
{
weight_weight_txt.Text = w.Replace(' ', '0');
w = string.Empty;
}
break;
case "7":
method.Invoke(calss, new object[] { SpCom, txt, weight_weight_txt, richTextBox2 });
break;
}
}
catch (Exception xx)
{
//richTextBox1.AppendText(xx.ToString());
}
}));
}
}
catch (Exception)
{
}
}
4、以下是完整代码(需要可运行源码可以联系我无偿提供):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SerialTool
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int substrStart = 2;
int substrLen = 6;
private void Form1_Load(object sender, EventArgs e)
{
DataTable BaudModle = new DataTable();
BaudModle.Columns.AddRange(new DataColumn[] { new DataColumn("id"), new DataColumn("name") });
BaudModle.Rows.Add("1", "ReadExisting");
BaudModle.Rows.Add("2", "ReadLine");
BaudModle.Rows.Add("3", "ReadExisting(两次拼接)");
BaudModle.Rows.Add("4", "ReadExisting(三次拼接)标准");
BaudModle.Rows.Add("5", "ReadExisting(三次拼接)咸宁");
BaudModle.Rows.Add("6", "ReadExisting(三次拼接)黄冈");
BaudModle.Rows.Add("7", "其它");
d_BaudModle.DataSource = BaudModle;
d_BaudModle.ValueMember = "id";
d_BaudModle.DisplayMember = "name";
setCombobox();
}
private void setCombobox()
{
cbBT.SelectedIndex = cbCK.SelectedIndex = cbJO.SelectedIndex = cbTZ.SelectedIndex = d_BaudModle.SelectedIndex = 0;
}
public bool ReceiveData = false;
private void button1_Click(object sender, EventArgs e)
{
t = (d_BaudModle.SelectedIndex + 1).ToString();
this.button1.Text = button1.Text == "开始" ? "停止" : "开始";
if (this.button1.Text == "开始")
{
ReceiveData = false;
CloseCom();
}
else
{
ReceiveData = true;
OpenCom();
}
if (t == "7")
{
richTextBox2.Visible = true;
richTextBox1.Visible = false;
richTextBox1.BringToFront();
}
else
{
richTextBox2.Visible = false;
richTextBox1.Visible = true;
richTextBox1.BringToFront();
}
}
string w = string.Empty;
private void serialWeight_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
{
}
/// <summary>
/// 获取指定的实例
/// </summary>
/// <returns></returns>
object getClass()
{
Assembly assembly = Assembly.LoadFile(Application.StartupPath + "\\" + textBox_dtk.Text.Trim() + ".dll");
Type t = assembly.GetType(textBox_dtk.Text.Trim());
object obj = assembly.CreateInstance(t.ToString());
return obj;
}
private void OpenCom()
{
try
{
if (SpCom.IsOpen)
{
SpCom.Close();
}
if (t == "7")
{
calss = getClass();
method = calss.GetType().GetMethod("GetData");
}
//else
//{
substrStart = Convert.ToInt32(tbStart.Text);
substrLen = Convert.ToInt32(tbLen.Text);
//"COM3"; //
SpCom.PortName = cbCK.Text;// comboBox1.SelectedItem.ToString();
SpCom.BaudRate = Convert.ToInt32(cbBT.Text);// 2400;
SpCom.Parity = (Parity)cbJO.SelectedIndex;// Parity.Even;
SpCom.DataBits = Convert.ToInt32(tbSJ.Text);
SpCom.StopBits = (StopBits)cbTZ.SelectedIndex;
//}
SpCom.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
// throw;
}
}
private void CloseCom()
{
if (SpCom.IsOpen)
{
SpCom.Close();
}
}
object calss;
MethodInfo method;
string t;
private void serialWeight_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (ReceiveData)
{
//richTextBox1.AppendText(t + "\r\n");
weight_weight_txt.Invoke(new EventHandler(delegate
{
try
{
string txt = string.Empty;
switch (t)
{
case "1":
txt = SpCom.ReadExisting();
richTextBox1.AppendText(txt + "\r\n");
txt = txt.Substring(substrStart, substrLen);
weight_weight_txt.Text = txt.Trim();
break;
case "2":
txt = SpCom.ReadLine();
richTextBox1.AppendText(txt + "\r\n");
txt = txt.Substring(substrStart, substrLen);
weight_weight_txt.Text = txt.Trim();
break;
case "3":
txt = SpCom.ReadExisting();
richTextBox1.AppendText(txt + "\r\n");
if (txt.Length == 8)
{
if (txt.Contains(' '))
{
w = txt.Split(' ')[1];
}
else
{
w += txt.Substring(0, 2);
}
if (w.Length == 6)
{
weight_weight_txt.Text = w;
w = string.Empty;
}
}
break;
case "4":
txt = SpCom.ReadExisting();
richTextBox1.AppendText(txt + "\r\n");
if (txt.Contains(")"))
{
w = txt.Substring(4, 4);
}
if (w != "" && !txt.Contains(")") && txt.Contains(" "))
{
w += txt.Substring(0, 2);
}
if (w.Length == 6 && !w.Contains(')'))
{
weight_weight_txt.Text = w.Replace(' ', '0');
w = string.Empty;
}
break;
case "5":
txt = SpCom.ReadExisting();
richTextBox1.AppendText(txt + "\r\n");
if (txt.Length > 6 && !txt.Contains(" "))
{
w = txt.Substring(4, 4);
}
if (txt.Length > 6 && txt.IndexOf(" ") == 2)
{
w += txt.Substring(0, 2);
}
if (w.Length == 6 && txt.IndexOf(" ") != 2 && txt.IndexOf(" ") != 3)
{
weight_weight_txt.Text = w.Replace(' ', '0');
w = string.Empty;
}
break;
case "6":
txt = SpCom.ReadExisting();
richTextBox1.AppendText(txt + "\r\n");
if (txt.Length > 6 && txt.IndexOf(" ") != 2)
{
w = txt.Substring(4, 4);
}
if (txt.Length > 6 && txt.IndexOf(" ") == 2)
{
w += txt.Substring(0, 2);
}
if (w.Length == 6 && txt.IndexOf(" ") != 2)
{
weight_weight_txt.Text = w.Replace(' ', '0');
w = string.Empty;
}
break;
case "7":
method.Invoke(calss, new object[] { SpCom, txt, weight_weight_txt, richTextBox2 });
break;
}
}
catch (Exception xx)
{
//richTextBox1.AppendText(xx.ToString());
}
}));
}
}
catch (Exception)
{
}
}
private void d_BaudModle_SelectedIndexChanged(object sender, EventArgs e)
{
//bdMode = d_BaudModle.SelectedValue.ToString();
}
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
{
richTextBox1.SelectAll();
}
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "动态库文件|*.dll";
if (ofd.ShowDialog() == DialogResult.OK)
{
//MessageBox.Show(ofd.SafeFileName);
try
{
File.Copy(ofd.FileName, Application.StartupPath + "\\" + ofd.SafeFileName, true);
textBox_dtk.Text = ofd.SafeFileName.Split('.')[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}