首页 > 解决方案 > 使用定时器和任务的 Arduino 到 C# 实时数据传输

问题描述

问题:在 Form1 上声明的“str”变量未在Timer1_Tick()方法中读取。输入来自连接到多个传感器的 Arduino。传感器输入组合成一个字符串(例如 [1,2,4,5,6])。对于这段代码,我只需要显示该字符串。非常感谢您对此事的任何帮助。

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            SerialPort currentPort = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One);
            currentPort.Open();
            string str = currentPort.ReadLine();
        }
        private void Timer1_Tick(object sender, EventArgs e)
        {
            Task.Run(() => {
                this.BeginInvoke((Action)(() => { label1.Text = str; }));
            });

        }

        private void Button1_Click(object sender, EventArgs e)
        {//Start
            timer1.Start();
        }

        private void Button2_Click(object sender, EventArgs e)
        {//Stop
            timer1.Stop();
        }
    }
}

标签: c#variablestimerarduinotask

解决方案


在 Form1 上声明的“str”变量未在 Timer1_Tick 中读取。

原因是:str变量是在 上声明的Form1_Load,所以它是一个局部变量。仅在类内部声明它Form1,但在方法外部声明它。这样,它将是一个全局变量,可以从Form1类中的任何方法访问,包括计时器方法。


推荐阅读