Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: Meta en 30 Diciembre 2021, 06:11 am



Título: Al recibir datos, se me comen las palabras o faltan caracteres
Publicado por: Meta en 30 Diciembre 2021, 06:11 am
Buenas:

Al recibir datos por puerto serie, muchas veces se me come las palabras.

¿Hay alguna forma que no fallen las entradas de mensajes por puerto serie?

Dejo el código fuente aquí.

Código
  1. using System;
  2. using System.IO.Ports;
  3. using System.Text;
  4. using System.Threading;
  5. using System.Windows.Forms;
  6.  
  7. namespace Velocímetro_Arduino_Puerto_serie_01
  8. {
  9.    public partial class Form1 : Form
  10.    {
  11.        // Utilizaremos un string como buffer de recepción.
  12.        string recibidos;
  13.  
  14.        public Form1()
  15.        {
  16.            InitializeComponent();
  17.        }
  18.  
  19.        private void Form1_Load(object sender, EventArgs e)
  20.        {
  21.            // Añado los puertos disponible en el PC con SerialPort.GetPortNames() al comboBox_Puerto.
  22.            try
  23.            {
  24.                comboBox_Puerto.DataSource = SerialPort.GetPortNames();
  25.            }
  26.  
  27.            catch
  28.            {
  29.                MessageBox.Show("No encuentra ningún puerto físico ni virtual.", "Aviso:",
  30.                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
  31.            }
  32.  
  33.            // // Añade puertos disponibles físicos  y virtuales.
  34.            serialPort1.PortName = comboBox_Puerto.Text.ToString();
  35.        }
  36.  
  37.        #region Funciones.
  38.  
  39.        void UsbConectado()
  40.        {
  41.            byte[] miBuffer = Encoding.ASCII.GetBytes("USB_CONECTADO");
  42.            serialPort1.Write(miBuffer, 0, miBuffer.Length);
  43.        }
  44.  
  45.        void UsbDesconectado()
  46.        {
  47.            byte[] miBuffer = Encoding.ASCII.GetBytes("USB_DESCONECTADO");
  48.            serialPort1.Write(miBuffer, 0, miBuffer.Length);
  49.        }
  50.  
  51.        // Detecta USB o puerto serie virtual cuando lo conecta y desconecta del cable.
  52.        protected override void WndProc(ref Message USB)
  53.        {
  54.            if (USB.Msg == 0x219)
  55.            {
  56.                comboBox_Puerto.DataSource = SerialPort.GetPortNames();
  57.            }
  58.  
  59.            // Detecta si hay cambios en el usb y si los hay los refleja.
  60.            base.WndProc(ref USB);
  61.        }
  62.  
  63.        // Procesar los datos recibidos en el buffer y extraer las tramas completas.
  64.        void Actualizar(object sender, EventArgs e)
  65.        {
  66.            // Asignar el valor de la trama al label_Recibir_Km.
  67.            label_Recibir_Km.Text = recibidos;
  68.  
  69.            switch (recibidos)
  70.            {
  71.                case "OK":
  72.                    byte[] miBuffer = Encoding.ASCII.GetBytes("Conectado.      ");
  73.                    serialPort1.Write(miBuffer, 0, miBuffer.Length);
  74.                    label_Recibir_Km.Text = "Arduino conectado.";
  75.                    break;
  76.                default:
  77.                    break;
  78.            }
  79.  
  80.            // Limpiar.
  81.            recibidos = "";
  82.        }
  83.        #endregion
  84.  
  85.        #region Botones.
  86.        private void button_Conectar_Click(object sender, EventArgs e)
  87.        {
  88.            try
  89.            {
  90.                serialPort1.PortName = comboBox_Puerto.Text.ToString(); // Puerto seleccionado previamente.
  91.                serialPort1.Open(); // Abrir puerto.
  92.                UsbConectado();
  93.                comboBox_Puerto.Enabled = false;
  94.                comboBox_Baudios.Enabled = false;
  95.                button_Conectar.Enabled = false;
  96.                button_Desconectar.Enabled = true;
  97.                button_Enviar.Enabled = true;
  98.            }
  99.  
  100.            catch
  101.            {
  102.                MessageBox.Show("El puerto no existe.", "Aviso:",
  103.                MessageBoxButtons.OK, MessageBoxIcon.Warning);
  104.            }
  105.        }
  106.  
  107.        private void button_Desconectar_Click(object sender, EventArgs e)
  108.        {
  109.            UsbDesconectado();
  110.            serialPort1.Close(); // Cerrar puerto.
  111.            comboBox_Puerto.Enabled = true;
  112.            comboBox_Baudios.Enabled = true;
  113.            button_Conectar.Enabled = true;
  114.            button_Desconectar.Enabled = false;
  115.            button_Enviar.Enabled = false;
  116.        }
  117.  
  118.        private void button_Enviar_Click(object sender, EventArgs e)
  119.        {
  120.            byte[] miBuffer = Encoding.ASCII.GetBytes("KM" + textBox_Km.Text);
  121.            serialPort1.Write(miBuffer, 0, miBuffer.Length);
  122.        }
  123.        #endregion
  124.  
  125.        // Al cerrar el formulario, cierra el puerto si está abierto.
  126.        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  127.        {
  128.            try
  129.            {
  130.                // Al cerrar este programa, indica a Arduino cerrado.
  131.                // Arduino sigue con su rutina al detectar CERRADO.
  132.                byte[] miBuffer = Encoding.ASCII.GetBytes("C#_CERRADO");
  133.                serialPort1.Write(miBuffer, 0, miBuffer.Length);
  134.  
  135.                // Cerrar puerto.
  136.                serialPort1.Close();
  137.            }
  138.  
  139.            catch (Exception error)
  140.            {
  141.                MessageBox.Show(error.Message, "Aviso:",
  142.                MessageBoxButtons.OK, MessageBoxIcon.Warning);
  143.            }
  144.        }
  145.  
  146.        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
  147.        {
  148.            // Acumula los caracteres recibidos a nuestro "buffer" string.
  149.            recibidos += serialPort1.ReadExisting();
  150.  
  151.            // Invocar o llamar al proceso de tramas.
  152.            Invoke(new EventHandler(Actualizar));
  153.        }
  154.    }
  155. }
  156.