串口通讯显示 [英] Serial port communication display

查看:53
本文介绍了串口通讯显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用串行端口通信进行聊天.这个聊天必须在 WPF 项目中有一个界面,我已经制作了我的界面和所有东西.我被困在通过串行端口接收响应.我已经尝试从串行端口添加一个 DataReceived 事件,但恐怕我用错了,因为我以前从未用 C# 编程过.这是一个非常简单的代码.我需要做的是从串行端口接收信息并将其显示在文本块中,就像在简单的聊天窗口中一样.

I'm trying to make a chat with serial port communication. This chat has to have an interface in a WPF Project, I already made my interface and everything. I'm stuck in receiving the response through the serial port. I already tried adding a DataReceived event from the serial port but I'm afraid I'm using it wrong since I have never programmed in C# before. It is a really simple code. What I need to do is receive the information from the serial port and display it in a text block as it would look in a simple chat window.

        InitializeComponent();
        _serialPort = new SerialPort();

        foreach (string s in SerialPort.GetPortNames())
        {
            listaComs.Items.Add(s);
        }


    }

    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        visor.Inlines.Add("Data Received:");
        visor.Inlines.Add(indata);
    }
    private void enviarClick(object sender, RoutedEventArgs e)
    {
        _serialPort.WriteLine(escribir.Text);
        visor.Inlines.Add("Yo: " + escribir.Text + Environment.NewLine);
    }

    private void cambiarTexto(object sender, MouseButtonEventArgs e)
    {
        if (escribir.Text == "Escriba su texto")
        {
            escribir.Text = "";
        }
    }

    private void inicializarSerial()
    {
        // Poner las propiedades correctas.
        _serialPort.BaudRate = 9600;
        _serialPort.Parity = Parity.None;
        _serialPort.StopBits = StopBits.One;
        _serialPort.DataBits = 8;
        _serialPort.Handshake = Handshake.None;
        _serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        // Poner los timeouts de escritura y lectura
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;
    }

    private void conectarCom(object sender, RoutedEventArgs e)
    {
        string seleccion = listaComs.SelectedItem.ToString();
        _serialPort.PortName = seleccion;
        inicializarSerial();
        _serialPort.Open();
        _continue = true;
        visor.Text = "";
    }

    private void desconectarCom(object sender, RoutedEventArgs e)
    {
        _serialPort.Close();
    }

当我在 .exe 文件中运行它时,它会崩溃并出现 InvalidOperationException 和内部异常(已翻译):

When I run this in the .exe file it crashes down with an InvalidOperationException with inner exception (translated):

"实现调用的子进程无法获得访问权限对象,因为专有是另一个子进程."

"The subprocess that realized the call cannot gain Access to this object because the propietary is another subprocess."

推荐答案

事件是从调用它们的线程中触发的,在串行端口(或任何通信层)的情况下,这肯定会 不在 UI 线程上.

Events are fired from the thread that invoked them, and in the case of a serial port (or any comms layer), this is going to definitely not be on the UI thread.

但是,UI 操作必须在 UI 线程上完成.所以下面的代码会失败:

However, UI operations must be done on the UI thread. So the code below will fail:

    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();
    visor.Inlines.Add("Data Received:");
    visor.Inlines.Add(indata);

因为您正在修改错误线程中的 UI 元素.解决方案是使用 BeginInvoke (MSDN) 将操作编组到 UI 线程上:

Because you are modifying a UI element from the wrong thread. The solution is to use BeginInvoke (MSDN) to marshal the operation onto the UI thread:

    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();

    Dispatcher.BeginInvoke(() =>
    {
       visor.Inlines.Add("Data Received:");
       visor.Inlines.Add(indata);
    }, null);

附注.您的异常的翻译似乎不正确;如果这是问题,您将看到的例外是(英文):

PS. The translation of your exception didn't seem right; if this was the issue, the exception you will see is (in English):

跨线程操作无效:控制从其他线程访问比创建它的线程.

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.

(或非常相似的东西).我无法识别提供的文本,根据您的代码,您遇到的似乎是这种情况.

(Or something very similar). I didn't recognize the provided text, and given your code, it looks like this is what you encountered.

这篇关于串口通讯显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆