Go Down

Topic: C# Form read data LAG (Read 487 times) previous topic - next topic

qkqk01qk

I am now making a C# Interface to read the data from Arduino (Serial.print).

However, when the C# Form ran about over 1 minute, it is so lag and even cannot control the Form.

How to solve this problem? maybe it is about memory?

Arduino: "Serial.print" a number with "0.5s" interval
C#: using timer and SerialPort to read with "0.5s" interval



C# code:

Code: [Select]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public SerialPort myport = new SerialPort();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            myport.BaudRate = 9600;
            myport.PortName = "COM8";
            myport.Open();
            timer1.Interval = 500;
        }

        public void timer1_Tick(object sender, EventArgs e)
        {           
            string data_rx = myport.ReadLine();
            label1.Text = data_rx;
            timer1.Start();           
        }
    }
}



---------------------------------------------------------------------------------------------------------------------------------


Arduino code

Code: [Select]

int TouchSensor = 0;

void setup() {
  Serial.begin(9600);
  pinMode(TouchSensor, INPUT);
}

void loop() {
  if(digitalRead(TouchSensor)==HIGH)       //Read Touch sensor signal
   {
    Serial.println("1");
   }
  else
   {
    Serial.println("0");
   }
  delay(500);
}



Thanks! :)

horace

rather tha usinga timer event use a SerialPort.dataReceived event, e.g.
Code: [Select]

private void myport_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string data_rx = myport.ReadLine();
            label1.Text = data_rx;

        }

however, you should avoid accessing GUI components from the SerialPort event handler as it is not thread safe

PaulS

Quote
however, you should avoid accessing GUI components from the SerialPort event handler as it is not thread safe
You can use the Invoke() mechanism to allow thread-safe update of GUI components.
The art of getting good answers lies in asking good questions.

qkqk01qk

Finally I found a solution and running smooth.

http://forum.arduino.cc/index.php?topic=199056.0#msg1482780

Thanks

Go Up