Click here to Skip to main content
15,357,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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);
                }
            }


C#
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();
            }
        }
Posted
Updated 21-Mar-19 3:22am

1 solution

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:
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.
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.
   
Comments
CPallini 21-Mar-19 9:37am
   
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900