PhoenixLament
PhoenixLament

Reputation: 741

Reading from SerialPort I/O Timer c# Visual Studios 2010

I am currently working on a project where I am reading data off a custom made PCB using the SerialPort library in Visual Studios 2010 c#.

I am currently attempting to read a certain type of data given to me as bytes of data from the device via button click, and wait five seconds before timing out if no response from device.

However for some reason the timer is being glitchy and often times expires before five seconds have elapsed, thus stopping valid data from being stored. Below is my code used, can someone point out my flaw? I suspect the event timer function from System.Windows.Forms.Timer that I use is incorrect.

Button Click

    bool flag = false;
    private void btnGetData_Click(object sender, EventArgs e)
    {

        string command = "*data#";//make string command to send
        sendCommand(command);
        flag = true;
        gui.Timer.Interval = timerlength;
        gui.Timer.Enabled = true;
        gui.Timer.Tick += new EventHandler(Timer_Tick);


    }

Timer Event Handler

    private void readVarsTimer_Tick(object sender, EventArgs e)
    {
       if (flag == true)
        {
            flag = false;//set flag low
            print("Data Timer Expired, Run Command Again.");
            gui.Timer.Stop();//stop timer
            gui.Timer.Enabled = false; //event over
            timerlength = 5000;//reset timer

        }
    }

Serial Port reading data in, please assume settings for Serial Port is correct, as any transmission or received data not using a timer works just fine.

            if (flag == true)
            {
              //code to read data in, and parse to display in text boxes correct 
              flag = false; 
            }

Other important notes:

Upvotes: 0

Views: 1894

Answers (1)

Hans Passant
Hans Passant

Reputation: 941218

There's not enough code to make the call. But two basic problems stand out: you can enable a timer that might already be enabled. Which doesn't do anything, your timer will expire too soon. And a more serious problem, you keep adding event handlers. So it the timer expires then the Tick event handler will run multiple times.

You will need to subscribe the Tick event just once, do so in the constructor of your class.

And you have to make sure that the timer is disabled before you start it. Do so by setting its Enabled property back to false in the Tick event handler and when you received the response. Presumably the latter is missing. Raise an InvalidOperationException when it is already enabled it the btnGetData_Click() method since it is a logical error if that's the case. Or force Enabled = false first if abandoning the attempt to get a response is legal.

Upvotes: 1

Related Questions