Search code examples
c#variablestimerarduinotask

Arduino to C# RealTime data transfer using timer and task


The problem: The "str" variable that is declared on Form1 isn't being read in Timer1_Tick() method. The input is coming from an Arduino that is connected to multiple sensors. The sensor inputs are combined into a single string (example [1,2,4,5,6]). For this code, I just need to display that string. Any help on the matter is much appreciated.

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();
        }
    }
}

Solution

  • You need to declare the "str" variable in the Form1 scope, use this code:

    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            string str;
            public Form1()
            {
                InitializeComponent();
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                SerialPort currentPort = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One);
                currentPort.Open();
                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();
            }
        }
    }