C sharp - No recibe bien los datos

 
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

No recibe bien los datos

Publicado por Meta (122 intervenciones) el 01/04/2021 05:33:50
Buenas:

Me está dando resultados diferentes de un terminal que el propio mio en hexadecimal y no se el motivo. Cuando los datos recibidos son los mismos.
1659350

Ver imagen.

Quiero saber el motivo. Muchas gracias.

Configuración puerto serie.
1659357
Ver zoom.

Código C#:
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
using System;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace Terminal_UPS_SAI_02
{
    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)
        {
            try
            {
                // Añado los puertos disponible en el PC con SerialPort.GetPortNames() al comboBox_Puerto.
                comboBox_Puerto.DataSource = SerialPort.GetPortNames();
 
                // Añade puertos disponibles físicos  y virtuales.
                serialPort1.PortName = comboBox_Puerto.Text.ToString();
 
                // Añadir en la variable recibidos datos codificados.
                recibidos += serialPort1.Encoding = Encoding.GetEncoding(437);
 
                // Añadir datos recibidos en el evento.
                serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            }
 
            catch
            {
                MessageBox.Show("No encuentra ningún puerto físico ni virtual.", "Aviso:",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
 
        // 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);
        }
 
        private void button_Conectar_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName = comboBox_Puerto.Text.ToString(); // Puerto seleccionado previamente.
                serialPort1.BaudRate = Convert.ToInt32(comboBox_Baudios.Text); // Baudios.
                serialPort1.Open(); // Abrir puerto.
                comboBox_Puerto.Enabled = false;
                comboBox_Baudios.Enabled = false;
                button_Conectar.Enabled = false;
                button_Desconectar.Enabled = true;
                groupBox_Control_Zumbador.Enabled = true;
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message, "Aviso:",
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
 
        private void button_Desconectar_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Close(); // Cerrar puerto.
                comboBox_Puerto.Enabled = true;
                comboBox_Baudios.Enabled = true;
                button_Conectar.Enabled = true;
                button_Desconectar.Enabled = false;
                groupBox_Control_Zumbador.Enabled = false;
            }
 
            catch (Exception error)
            {
                MessageBox.Show(error.Message, "Aviso:",
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
 
        // Al cerrar el formulario, cierra el puerto si está abierto.
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                serialPort1.Close(); // Cerrar puerto.
            }
 
            catch (Exception error)
            {
                MessageBox.Show(error.Message, "Aviso:",
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
 
        // Al recibir datos.
        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));
        }
 
        // Procesar los datos recibidos en el bufer y extraer tramas completas.
        private void Actualizar(object sender, EventArgs e)
        {
 
            // Asignar el valor de la trama al richTextBox.
            richTextBox1.Text += recibidos;
 
            // Pasar a hexadecimal.
            foreach (byte b in recibidos)
            {
                // x = minúscula, X = mayúscula.
                richTextBox1.Text += b.ToString("X2");
            }
 
            // Nueva línea.
            richTextBox1.Text += Environment.NewLine;
 
            // Pasar a binario.
            foreach (string leer in recibidos.Select(c => Convert.ToString(c, 2)))
 
            {
                richTextBox1.Text += leer.ToString();
            }
 
            // Nueva línea.
            richTextBox1.Text += Environment.NewLine;
            richTextBox1.Text += Environment.NewLine;
 
            // Selecciona la posición final para leer los mensajes entrantes.
            richTextBox1.SelectionStart = richTextBox1.Text.Length;
 
            // Mantiene el scroll en la entrada de cada mensaje.
            richTextBox1.ScrollToCaret();
 
            // Limpiar.
            recibidos = "";
        }
 
        private void button_Activar_Click(object sender, EventArgs e)
        {
            //byte[] mBuffer = Encoding.ASCII.GetBytes("K60:1\r"); // Comando K60:1 activar.
            byte[] mBuffer = Encoding.ASCII.GetBytes("X87\r"); // Comando X87 Flags.
            serialPort1.Write(mBuffer, 0, mBuffer.Length);
        }
 
        private void button_Desactivar_Click(object sender, EventArgs e)
        {
            byte[] mBuffer = Encoding.ASCII.GetBytes("K60:0\r"); // Comando K60:0 desactivar.
            serialPort1.Write(mBuffer, 0, mBuffer.Length);
        }
 
        private void button_Mute_temporal_Click(object sender, EventArgs e)
        {
            byte[] mBuffer = Encoding.ASCII.GetBytes("K60:2\r"); // Comando K60:2 Mute temporal.
            serialPort1.Write(mBuffer, 0, mBuffer.Length);
        }
 
        private void button_Limpiar_Click(object sender, EventArgs e)
        {
            // Limpiar.
            richTextBox1.Clear();
        }
    }
}

¿Alguna idea?

Saludos camaradas. ;)
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