BenAdamson
BenAdamson

Reputation: 675

Read from serial port for set amount of time?

I'm writing a C# program that reads numbers sent from an arduino to the serial port, puts them into a datatable and displays them in a chart. Currently when connect is clicked, it will continuously read in data from the serial port, by using a DataReceivedHandler event method.

I've got three buttons in the form:

When one of the buttons is clicked, the others are disabled and the clicked button is renamed to "Stop".

How would I enable this datareceivedhandler event to only trigger when desired as described above?

Upvotes: 0

Views: 812

Answers (1)

Andy P
Andy P

Reputation: 687

You can achieve what you want by adding and removing the serial port data received handler from within your button click events. Your second case would probably want to remove the handler in response to a timer tick event.

Something like this:

    private bool serialPortCapturing;

    private void btn1_Click(object sender, EventArgs e)
    {
        if (!serialPortCapturing)
        {
            serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort_DataReceived);
            serialPortCapturing = true;
        }
        else
        {
            serialPort.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(serialPort_DataReceived);
            serialPortCapturing = false;
        }
    }

Upvotes: 1

Related Questions