通过串口对磅秤集成,实时读取磅秤数据

通过串口对磅秤集成,实时读取磅秤数据

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);
                }
            }
        }
    }
}

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 25
    评论
Python是一种具有广泛用途的高级编程语言。在许多应用中,需要实时读取串口数据串口通信是一种非常常见的通信方式,它可用于连接外部设备,如传感器、执行器、调制解调器等。这里将讨论如何使用Python进行实时读取串口数据。 要实现Python实时读取串口数据,首先需要安装PySerial库。该库可以实现串行通信,并提供了强大的API,支持读写串口数据。为了使用它,需要在Python环境中使用pip install pyserial命令将其安装。 接下来,就可以使用Python代码从串口读取实时数据。以下是一些示例代码: import serial ser = serial.Serial('COM1', 9600, timeout=1) while True: data = ser.readline() if data: print(data) 这段代码使用serial模块打开串口“COM1”,波特率为9600,超时时间为1秒。然后在一个无限循环中,使用readline()方法读取串口数据。如果读到数据,就将其打印出来。 除了使用serial模块,还可以使用其他Python库来实现串口通信,如PyQtSerialPort、python-can等。这些库都可以实现实时读取串口数据的功能,只需要选择适合自己需求的库即可。 总的来说,Python是一种易于学习和使用的编程语言,并且有许多库可以扩展其功能。实时读取串口数据是一个很常见的需求,也是Python在工业、控制、物联网等领域中的一种应用。使用PySerial库等工具进行实时读取串口数据是实现该需求的一种常见方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 25
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_______________向阳、

您的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值