Click here to Skip to main content
15,394,707 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys, I got problem in display the Arduino data into my Windows Form. When I run my code the error "System.InvalidOperationException: 'Cross-thread operation not valid: Control 'hb' accessed from a thread other than the thread it was created on." are occur.

What I have tried:

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 HB_CRC
{
    public partial class Form1 : Form
    {
        int HeartBeats; 
        int Random1; 
        int Random2; 
        int CRC;
        public Form1()
        {
            InitializeComponent();
            Init();

            status.BackColor = Color.White;
        }

        private void Init()
        {
            string[] ports = SerialPort.GetPortNames();
            serialPort1.PortName = ports[0];
            serialPort1.BaudRate = 115200;

            try
            {
                serialPort1.Open();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Fail to Connect");
            }
        }
        
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string s = serialPort1.ReadLine();            
            string[] data = s.Split(',');            

            Int32.TryParse(data[0], out HeartBeats);
            Int32.TryParse(data[1], out Random1);
            Int32.TryParse(data[2], out Random2);
            Int32.TryParse(data[3], out CRC);

            hb.Text = Convert.ToString(HeartBeats);
            random1.Text = Convert.ToString(Random1);
            random2.Text = Convert.ToString(Random2);
            crc.Text = Convert.ToString(CRC);
        }
    }
}
Posted
Updated 18-May-22 22:56pm

1 solution

   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900