在 WPF 中从串口接收数据时做一些事情 [英] Doing something while receiving data from serial port in WPF

查看:125
本文介绍了在 WPF 中从串口接收数据时做一些事情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个程序,该程序将根据实时"接收到的数据以任何方式为椭圆着色.数据如:x1-1x2-1

I want to create program, that will color ellipse in any way depending on the received data in "real time". The data is like: x1-1, x2-1 etc.

我有一个奇怪的问题,我在调试时看到,填充椭圆的颜色应该改变,但它没有发生.

I have strange problem, I can see while debugging that, color of filling ellipse should change, but it doesn't happen.

我接收数据的部分代码:

Part of my code with receiving data:

 private void ReceiveData()
            {
                SerialPort serialPort = new SerialPort("COM1", 9600);
                serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                serialPort.Open();
            }

 private static void DataReceivedHandler(
                object sender,
                SerialDataReceivedEventArgs e)
            {
                SerialPort sp = (SerialPort)sender;
                string indata = sp.ReadExisting();
                if (indata.Contains(" "))
                {
                    testString = indata.Substring(0, 4);

                }
                Console.Write(indata);
            }

我可以在控制台中看到接收到的数据,即使点击按钮后,也开始接收数据.testString 是从indata 中提取单个x1-1,在接收数据时还在增长.我知道它不像它应该的那样工作,但现在没关系.

I can see received data in console, even after click on button, that starts receiving data. The testString is to extract single x1-1 from indata, that is still growing during receiving data. I know that it doesn't work like it should but it doesn't matter now.

按钮操作代码:

 private void button1_Click(object sender, RoutedEventArgs e)
        {
            ReceiveData();
            while (true)
            {
                if (testString == "x1-1") x1.Fill = Brushes.Blue;
                else x1.Fill = Brushes.Red;
            }
        }

x1 是我想要变成红色或蓝色的椭圆.我可以在这个函数中设置断点,我可以看到它应该改变.我认为问题是,该程序正在等待关闭端口并完成传输,然后它可能会改变,但我需要实时"拥有它.有人知道怎么做吗?

x1 is ellipse that I want to make red or blue. I can set the breakpoint in this function and I can see that it should change. I think the problem is, that program is waiting for close port and finish transmission, and then maybe it would change, but I need to have it in "real time". Anyone knows how to do it?

推荐答案

我相信您的处理方式是错误的.无需不断检查 teststring 的值,您只需启动通信端口侦听器并让它在后台运行 - 因为这将在它自己的线程上运行.然后你需要创建一个数据绑定到颜色.每当通信端口侦听器解析字符串时,它可以自动更新颜色.

I believe you are going about this the wrong way. Instead of constantly checking the value of teststring you need to just start the comm port listener and let it run in the background - as this will be on it's own thread. Then you need to create a Data Binding to the color. Whenever the comm port listener parses a string, it can automatically update the color.

首先,在 CommPort 类中:

First, in the CommPort class:

class MyCommPort : INotifyPropertyChanged
{
    SerialPort serialPort = null;
    public MyCommPort()
    {
        serialPort = new SerialPort("COM3", 9600);
        serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
        serialPort.Open();
    }
    ~MyCommPort()
    {
        serialPort.Close();
    }

    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string testString = null;
        string indata = sp.ReadLine();
        if (indata.Length >= 4)
        {
            testString = indata.Substring(0, 4);
            // Update the value
            if (testString == "x1-1") EllipseBrush = Brushes.Blue;
            else EllipseBrush = Brushes.Red;
        }
        Console.Write(testString);
    }

    // Create a property that will be bound
    private SolidColorBrush ellipseBrush = Brushes.Red;
    public SolidColorBrush EllipseBrush
    {
        get { return ellipseBrush; }
        set
        {
            ellipseBrush = value;
            OnPropertyChanged("EllipseBrush");
        }
    }

    // Extend the INotifyPropertyChanged interface
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            // Alert anyone bound to this that the value has changed
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

然后,将 Ellipse 的 DataContext 设置为 CommPort 类并将 Ellipse 的 Fill 属性绑定到 EllipseBrush.现在您所要做的就是启动 Commport 侦听器(ReceiveData();),颜色更新应该会自动发生.

Then, set the Ellipse's DataContext to the CommPort class and bind the Ellipse's Fill property to EllipseBrush. Now all you have to do is start the Commport listener (ReceiveData();) and the color updates should happen automatically.

例如:MainWindow.xaml

For example: MainWindow.xaml

<Window x:Class="delete_me.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Ellipse x:Name="ellipse" Fill="{Binding Path=EllipseBrush}" />
    </Grid>
</Window>

以及后面的代码:MainWindow.xaml.cs

And the code behind: MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ellipse.DataContext = new MyCommPort();
    }
}

这篇关于在 WPF 中从串口接收数据时做一些事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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