串口通信C# [英] Serialport communication C#

查看:73
本文介绍了串口通信C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在开发一个带有规模通信的Windows窗体。我不能从规模接收通信。已识别COM端口,但未收到Received方法的骚扰。以下是代码。



我尝试过:



Hi guys,
I am developing a Windows Form with communication with a scale. I can not receive communication from the scale. The COM port is identified, but the Received method is not harassed. Below is the code.

What I have tried:

<pre lang="c#">
if (cbParametro.Text != "" && cbAplicacao.Text != "")
            {
                txtP1.BackColor = Color.LightCoral;
                txtP2.BackColor = Color.LightCoral;
                string[] versaoRSplit = Variaveis.configuracao_bal.Split(';');
                
                //Porta: COM1; Velocidade: 9600; DataBit: 8
                string porta = versaoRSplit[0].Trim();
                string porta_conf = porta.Replace("Porta: ", "");
                string veloc = versaoRSplit[1].Trim();
                string veloc_conf = veloc.Replace("Velocidade: ", "");
                string databit = versaoRSplit[2].Trim();
                string databit_conf = databit.Replace("DataBit: ", "");

                try
                {
                    serialP.Close();
                }
                catch
                {

                }

                try
                {
                    int velocidade = Convert.ToInt32(veloc_conf);
                    int databit_int = Convert.ToInt32(databit_conf);
                    serialP.PortName = porta_conf;
                    serialP.BaudRate = velocidade;
                    serialP.Parity = Parity.None;
                    serialP.DataBits = databit_int;
                    serialP.StopBits = StopBits.One;
                    serialP.Handshake = Handshake.None;
                    serialP.RtsEnable = true;
                    serialP.DtrEnable = true;
                    serialP.DataReceived += new SerialDataReceivedEventHandler(serialP_DataReceived);
                    serialP.ReadTimeout = 500;
                    serialP.WriteTimeout = 500;
                    serialP.Open();
                    MessageBox.Show("Configuração realizada com sucesso.");

                    txtP1.BackColor = Color.LightGreen;
                    txtP1.Focus();
                    txtP2.BackColor = Color.LightCoral;
                }
                catch (Exception m)
                {
                    MessageBox.Show("Houve um erro ao testar as configurações informadas." + Environment.NewLine + "Detalhe: " + m.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }







private void serialP_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            MessageBox.Show("Mensagem Recebida.");
            if (txtP1.Focused)
            {
                string indata = serialP.ReadExisting();
                txtP1.Text = indata;
                txtP2.BackColor = Color.LightGreen;
                txtP2.Focus();
            }
            else if (txtP2.Focused)
            {
                string indata = serialP.ReadExisting();
                txtP2.Text = indata;
                MessageBox.Show("Pesagem foi realizada com sucesos.");
            }
            else
            {
                string indata = serialP.ReadExisting();
                txtP1.Text = indata;
                MessageBox.Show("Data Received:" + indata, "Aviso");
                txtP2.BackColor = Color.LightGreen;
                txtP2.Focus();
            }
        }

推荐答案

首先使用Hyperterminal或类似的方式在两个方向进行通信:确定可以使用coms以及确切需要什么参数。然后硬连接这些参数并在不使用事件的情况下进行基本测试,以确保您的代码基本连接。展开它以使用您的配置信息。并检查。最后添加事件处理。



但是......还阅读文档:SerialPort.DataReceived Event(System.IO.Ports)| Microsoft Docs [ ^ ]

Start by communicating in both directions using Hyperterminal or similar: establish that coms is possible and exactly what parameters are needed. Then hard wire those parameters in and do a basic test without using events to ensure that your code is basically connected. Expand that to use your config info. and check that. Finally add event handling.

But ... also read the documentation: SerialPort.DataReceived Event (System.IO.Ports) | Microsoft Docs[^]
Quote:

DataReceived事件是从SerialPort对象接收数据时在辅助线程上引发。因为此事件是在辅助线程而不是主线程上引发的,所以尝试修改主线程中的某些元素(例如UI元素)可能会引发线程异常。如果有必要修改主窗体或控件中的元素,请使用Invoke发回更改请求,这将在正确的线程上执行工作。

The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread.

因此您无法访问DataReceived事件处理程序中的UI元素或者它将抛出一个交叉线程异常,这可能是你的代码发生的事情。

So you can't access UI elements in your DataReceived event handler or it will throw a cross threading exception, which is probably what is happening with your code.


这篇关于串口通信C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆