使用arduino按端口显示增量后如何清理标签?

我正在尝试增加 Arduino 中的一个值并将其发送到端口,然后将其实时显示在标签中。


即使我放置并延迟(200)和Thread.sleep(200);


namespace Receiver

{

    public partial class Form1 : Form

    {

        SerialPort port;

        public Form1()

       {


            InitializeComponent();

            this.FormClosed += new FormClosedEventHandler(Form1_FormClosed);

            if (port == null)

            {

                port = new SerialPort("COM9", 9600);//Set your board COM

                port.Open();

            }



        }

        void Form1_FormClosed(object sender, FormClosedEventArgs e)

        {

            if (port != null && port.IsOpen)

            {

                port.Close();

            }

        }


        private void Afisare_Click(object sender, EventArgs e)

        {

            while (true)

            {

                string a = port.ReadExisting();

                afisare.Text = a;

                Thread.Sleep(200);

            }

        }

    }

}

在变化中,我得到了所有的值,一个接一个,在屏幕上显示其中一些。

https://img4.mukewang.com/64e1c539000199e319171036.jpg

大话西游666
浏览 121回答 1
1回答

郎朗坤

您正在处理程序中运行无限循环Afisare_Click,该循环与您的 UI 在同一线程中运行。这意味着 UI 将无法呈现控件更改。Thread.Sleep代码将上下文切换到其他线程,但不是 UI 线程。您的方法应该是使用Timer。public partial class Form1 : Form{    private Timer _timer;    public Form1()    {        InitializeComponent();    }    private void Form1_Load(object sender, EventArgs e)    {        _timer = new Timer();        _timer.Interval = 200;        _timer.Tick += _timer_Tick;        _timer.Enabled = true;        _timer.Start();    }    private void _timer_Tick(object sender, EventArgs e)    {        // This function will be called every 200 ms.        // Read the information from port, update the UI.        string a = port.ReadExisting();        afisare.Text = a;    }    private void Form1_FormClosed(object sender, FormClosedEventArgs e)    {        _timer.Stop();        if (port != null && port.IsOpen)        {            port.Close();        }    }}
打开App,查看更多内容
随时随地看视频慕课网APP