C sharp - Se come las palabras

 
Vista:
sin imagen de perfil
Val: 168
Bronce
Ha mantenido su posición en C sharp (en relación al último mes)
Gráfica de C sharp

Se come las palabras

Publicado por Meta (122 intervenciones) el 01/01/2022 10:29:30
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í.

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

Feliz año nuevo 2022.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder