Receiving data via serial connection C#

Asked

Viewed 3,855 times

10

I need to do a program that has to send a command to a radio connected via serial port and this returns your ID. The connection to the port and the sending of data is ok, when I send something the light flashes. But I need your return and from what I saw in debug the program does not enter the serial classPort1_DataReceived. What could be?

Follows the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;  // necessário para ter acesso as portas     


namespace serialteste
{
public partial class Form1 : Form
{
    string RxString;

    public Form1()
    {
        InitializeComponent();

    }


    private void atualizaListaCOMs()
    {
        int i;
        bool quantDiferente;    //flag para sinalizar que a quantidade de portas mudou

        i = 0;
        quantDiferente = false;

        //se a quantidade de portas mudou
        if (comboBox1.Items.Count == SerialPort.GetPortNames().Length)
        {
            foreach (string s in SerialPort.GetPortNames())
            {
                if (comboBox1.Items[i++].Equals(s) == false)
                {
                    quantDiferente = true;
                }
            }
        }
        else
        {
            quantDiferente = true;
        }

        //Se não foi detectado diferença
        if (quantDiferente == false)
        {
            return;                     //retorna
        }

        //limpa comboBox
        comboBox1.Items.Clear();

        //adiciona todas as COM diponíveis na lista
        foreach (string s in SerialPort.GetPortNames())
        {
            comboBox1.Items.Add(s);
        }
        //seleciona a primeira posição da lista
        comboBox1.SelectedIndex = 0;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //atualizaListaCOMs();

    }





    private void btConectar_Click(object sender, EventArgs e)
    {
        if (serialPort1.IsOpen == false)
        {
            try
            {


                serialPort1.PortName = comboBox1.Items[comboBox1.SelectedIndex].ToString();
                serialPort1.Open();

            }
            catch
            {
                return;

            }
            if (serialPort1.IsOpen)
            {
                btConectar.Text = "Desconectar";
                comboBox1.Enabled = false;

            }
        }
        else
        {

            try
            {
                serialPort1.Close();
                comboBox1.Enabled = true;
                btConectar.Text = "Conectar";
            }
            catch
            {
                return;
            }

        }
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        if (serialPort1.IsOpen == true)  // se porta aberta
            serialPort1.Close();            //fecha a porta


    }

    private void btEnviar_Click(object sender, EventArgs e)
    {
        if (serialPort1.IsOpen == true)          //porta está aberta
            serialPort1.Write(textBoxEnviar.Text);  //envia o texto presente no textbox
    }

    private void trataDadoRecebido(object sender, EventArgs e)
    {
        textBoxReceber.AppendText(RxString);
    }

    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {


        textBoxReceber.Text="alguma coisa recebeu";
        RxString = serialPort1.ReadExisting();              //le o dado disponível na serial
        this.Invoke(new EventHandler(trataDadoRecebido));   //chama outra thread para escrever o dado no text box
    }

    private void Atualizar_Click(object sender, EventArgs e)
    {
        atualizaListaCOMs();
    }      


}
}
  • Must be missing high related to serialPort1_DataReceived, some delegate for example to trigger this procedure. Check this in the documentation, SKD. @kaamis

  • @Hstackoverflow did a research but I didn’t understand it very well. Could you give me an example of how to make this relationship? I researched about delegates but could not insert in the project above!

  • Do you have any kind of documentation (SDK) of communication with this equipment? If you leave the link here, I can check to try a solution. @kaamis

  • See if this Codeproject article helps you http://www.codeproject.com/Articles/678025/Serial-Comms-in-Csharp-for-Beginners

  • Data receiving interruptions through the serial port sometimes didn’t work with me, more frequent problem in Mono C#. I recommend using this Nuget package: https://www.nuget.org/packages/SerialPortLib . For instructions for use and examples: https://github.com/genielabs/serialport-lib-dotnet .

1 answer

1

To trigger the process would be:

_serialPort.DataReceived += new SerialDataReceivedEventHandler(RecebeDadosSerial); 

However, it would be interesting to send us a manual about your device. You may not be sending anything to your serial. It may be that you need to send the ENQ command to get back, it can be done as follows:

string ENQ = "\u0005\r\n"; // -> \n padrão de Escape 
        _serialPort.Write(ENQ);
  • 1

    Thanks personally for the help, the problem was the command being sent and/or the speed of the radio (component connected via serial). The led flashed but did not come back with the answer, now everything is ok!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.