Passing value from a label to Arduino via serial

Asked

Viewed 126 times

1

I have developed a Windowsform that contains a label that checks CPU usage and displays its variations, and a button that connects the software to the Arduino in the available serial port. I also created a textBoxReceber, to check if Arduino is getting some value, but that’s the problem, I’m not able to send the updated values to Arduino. Follow the code excerpt.

private void startMonitor()
    {
        MachineMonitor machineMonitor = new MachineMonitor("B-NTIDDT001");
        while (true)
        {

            var ram = "Mem RAM: " + machineMonitor.GetUsageMemoryPercentage() + " %";
            var cpu = "CPU: " + machineMonitor.GetUsageCPUPercentage() + " %";

            if (this.lblCpu.InvokeRequired)
            {
                lblCpu.Invoke((MethodInvoker)delegate () { this.lblCpu.Text = cpu; });
                this.ValorR = cpu;
            }
            else
            {
                this.lblCpu.Text = cpu;
            }

            Thread.Sleep(1000);
        }

Here is the method that takes CPU and RAM usage values and passes to lblCpu.

private void btConectar_Click(object sender, EventArgs e)
    {
        if (serialPort.IsOpen == false)
        {
            try
            {
                serialPort.PortName = comboBox1.Items[comboBox1.SelectedIndex].ToString();
                serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
                serialPort.Open();
            }
            catch
            {
                return;
            }
            if (serialPort.IsOpen == true)
            {
                btConectar.Text = "Desconectar";
                comboBox1.Enabled = false;
            }
        }
        else
        {
            try
            {
                serialPort.Close();
                comboBox1.Enabled = true;
                btConectar.Text = "Conectar";
            }
            catch
            {
                return;
            }
        }
    }

My connection to the serial ports available.

private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        lblCpu.Text = RxString;
        RxString = serialPort.ReadExisting();
        this.Invoke(new EventHandler(trataDadoRecebido));
    }

    private void trataDadoRecebido(object sender, EventArgs e)
    {
        textBoxReceber.AppendText(RxString);
    }

As you can see, I can’t get the data from lblCpu and forward it to my Arduino. I made an lblCpu_Click method, so it worked but I don’t want to have to keep clicking on lblCpu all the time, I would like you to update constantly without my interference.

1 answer

0

For this you must use a timer and make a time loop, ie you will choose a given time, with for example 1 in 1 minute for the method "lblCpu_Click be triggered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.