No recibo bien los datos.

Iniciado por Meta, Abril 01, 2021, 09:39:05 AM

Tema anterior - Siguiente tema

0 Miembros y 1 Visitante están viendo este tema.

Abril 01, 2021, 09:39:05 AM Ultima modificación: Abril 01, 2021, 04:05:41 PM por Gabriela
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.


You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login.

Quiero saber el motivo. Muchas gracias.

Configuración puerto serie.

You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login.

Código C#:
Código: text
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. ;)