SerialPort在c#中读取数据

时间:2017-08-04 09:18:45

标签: c#

我编写了一个程序,它连接到arduino的串口并接收设备发送的数据,但我在程序中显示它有一点问题,我从未看到过该错误。

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using port.dbDataSetTableAdapters;

namespace Factory_Performance
{
    public partial class FrmMain : Form
    {
        string s;
        Series series = new Series();
        SerialPort ComPort = new SerialPort();

        internal delegate void SerialDataReceivedEventHandlerDelegate(object sender, SerialDataReceivedEventArgs e);
        internal delegate void SerialPinChangedEventHandlerDelegate(object sender, SerialPinChangedEventArgs e);
        private SerialPinChangedEventHandler SerialPinChangedEventHandler1;
        delegate void SetTextCallback(int ReadByte);
        int InputData = 0;


        private int CountData;
        private string StrData;
        double[] Values;
        public FrmMain()
        {
            InitializeComponent();
            SerialPinChangedEventHandler1 = new SerialPinChangedEventHandler(PinChanged);
            ComPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
        }

        private double calculate_input(int s2, int s3)
        {
            return double.Parse(s2.ToString() + "/" + s3.ToString());
        }

        private void GetAllIDInDB()
        {
            tblIDTableAdapter.Fill(dbDataSet.TblID);
            CmbID.Items.Clear();

            for (int i = 0; i < dbDataSet.TblID.Rows.Count; i++)
                CmbID.Items.Add(dbDataSet.TblID.Rows[i]["ID"].ToString());
        }
        private void GetAllID_DetailsInDB(int ID)
        {
            tblID_DetailsTableAdapter.FillByID(dbDataSet.TblID_Details, ID);
            LstItems.Items.Clear();
            for (int i = 0; i < dbDataSet.TblID_Details.Rows.Count; i++)
                LstItems.Items.Add(dbDataSet.TblID_Details.Rows[i]["Value"].ToString());

        }

        private void GetInfoPorts()
        {
            try
            {
                string[] ArrayComPortsNames = null;
                int index = -1;
                string ComPortName = null;
                cboPorts.Items.Clear();
                cboBaudRate.Items.Clear();
                cboStopBits.Items.Clear();
                cboParity.Items.Clear();
                cboHandShaking.Items.Clear();
                //Com Ports
                ArrayComPortsNames = SerialPort.GetPortNames();
                do
                {
                    index += 1;
                    cboPorts.Items.Add(ArrayComPortsNames[index]);


                } while (!((ArrayComPortsNames[index] == ComPortName) || (index == ArrayComPortsNames.GetUpperBound(0))));
                Array.Sort(ArrayComPortsNames);

                if (index == ArrayComPortsNames.GetUpperBound(0))
                {
                    ComPortName = ArrayComPortsNames[0];
                }
                //get first item print in text
                cboPorts.Text = ArrayComPortsNames[0];
                //Baud Rate
                cboBaudRate.Items.Add(115200);
                cboBaudRate.Items.Add(300);
                cboBaudRate.Items.Add(600);
                cboBaudRate.Items.Add(1200);
                cboBaudRate.Items.Add(2400);
                cboBaudRate.Items.Add(9600);
                cboBaudRate.Items.Add(14400);
                cboBaudRate.Items.Add(19200);
                cboBaudRate.Items.Add(38400);
                cboBaudRate.Items.Add(57600);
                cboBaudRate.Items.ToString();
                //get first item print in text
                cboBaudRate.Text = cboBaudRate.Items[0].ToString();
                //Data Bits
                cboDataBits.Items.Add(8);
                cboDataBits.Items.Add(7);
                //get the first item print it in the text 
                cboDataBits.Text = cboDataBits.Items[0].ToString();

                //Stop Bits
                cboStopBits.Items.Add("One");
                cboStopBits.Items.Add("OnePointFive");
                cboStopBits.Items.Add("Two");
                //get the first item print in the text
                cboStopBits.Text = cboStopBits.Items[0].ToString();
                //Parity 
                cboParity.Items.Add("None");
                cboParity.Items.Add("Even");
                cboParity.Items.Add("Mark");
                cboParity.Items.Add("Odd");
                cboParity.Items.Add("Space");
                //get the first item print in the text
                cboParity.Text = cboParity.Items[0].ToString();
                //Handshake
                cboHandShaking.Items.Add("XOnXOff");
                cboHandShaking.Items.Add("None");
                cboHandShaking.Items.Add("RequestToSend");
                cboHandShaking.Items.Add("RequestToSendXOnXOff");
                //get the first item print it in the text 
                cboHandShaking.Text = cboHandShaking.Items[0].ToString();
            }
            catch
            {
                MessageBox.Show("خطا در گرفتن اطلاعات پورت");
            }
        }

        private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
        {

            InputData = ComPort.ReadByte();
            if (InputData != 0)
            {
             s= Convert.ToString(Convert.ToChar(InputData));

                this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
             label12.Text =Convert.ToString(s);
            }
        }
        private void SetText(int ReadByte)
        {
            this.LstGetInfo.Items.Add(ReadByte);
        }
        internal void PinChanged(object sender, SerialPinChangedEventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

            Values = new double[CountData];
            for (int i = 0; i < CountData; i++)
                Values[i] = (int)StrData[i];
            Array.Reverse(Values);
            chart1.Titles.Clear();
            chart1.Titles.Add(TxtTitle.Text);
            chart1.Series.Clear();
            series.Points.Clear();
            for (int i = 0; i < CountData; i++)
                series.Points.AddXY(TxtTitleSeries.Text + " " + i.ToString(), Values[i]);
            chart1.Series.Add(series);

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button3_Click(object sender, EventArgs e)
        {


        }

        private void CmbPalette_SelectedIndexChanged(object sender, EventArgs e)
        {
            chart1.Palette = (ChartColorPalette)CmbPalette.SelectedIndex;
        }

        private void CmbChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            series.ChartType = (SeriesChartType)CmbChartType.SelectedIndex;
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'dbDataSet.TblID_Details' table. You can move, or remove it, as needed.
            this.tblID_DetailsTableAdapter.Fill(this.dbDataSet.TblID_Details);
            // TODO: This line of code loads data into the 'dbDataSet.TblID' table. You can move, or remove it, as needed.
            this.tblIDTableAdapter.Fill(this.dbDataSet.TblID);
            GetInfoPorts(); 
            CmbPalette.SelectedIndex = 1;
            CmbChartType.SelectedIndex = 4;
            CountData = 0;
        }

        private void button3_Click_1(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click_2(object sender, EventArgs e)
        {

        }

        private void button4_Click_1(object sender, EventArgs e)
        {
          /*  if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                TxtPath.Text = openFileDialog1.FileName;
                string[] StrInfo = sr.ReadToEnd().Split(',');
                int[] Values2 = new int[StrInfo.Length - 4];
                for (int i = 0; i < StrInfo.Length-4; i++)
                    Values2[i] = int.Parse(StrInfo[i+4]);
                string StrTemp = "";


                foreach (int n in Values2)
                    StrTemp += (char)n;
                CountData = StrTemp.Length;
                StrData = StrTemp;
                Values = new int[CountData];
                for (int i = 0; i < CountData; i++)
                    Values[i] = (int)StrData[i];
                //Array.Reverse(Values);
                chart2.Palette = (ChartColorPalette)int.Parse(StrInfo[2]);
                series.ChartType = (SeriesChartType)int.Parse(StrInfo[3]);
                chart2.Titles.Clear();
                chart2.Titles.Add(StrInfo[0]);
                chart2.Series.Clear();
                series.Points.Clear();
                for (int i = 0; i < CountData; i++)
                    series.Points.AddXY(StrInfo[1] + " " + i.ToString(), Values[i]);
                chart2.Series.Add(series);

                StrTemp = "";
                Array.Reverse(Values2);
                foreach (int n in Values2)
                    StrTemp += (char)n;
                TxtDateRecovery.Text = DecryptStringAES(StrTemp, TxtKeyDecrypt.Text);
            }*/
        }

        private void btnGetSerialPorts_Click(object sender, EventArgs e)
        {
            GetInfoPorts();
        }

        private void btnPortState_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnPortState.Text == "ارتباط با دستگاه")
                {
                    btnPortState.Text = "قطع ارتباط با دستگاه";
                    ComPort.PortName = Convert.ToString(cboPorts.Text);
                    ComPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
                    ComPort.DataBits = Convert.ToInt16(cboDataBits.Text);
                    ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.Text);
                    ComPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandShaking.Text);
                    ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text);
                    ComPort.Open();
                    ComPort.Write("A");// کاراکتر شروع انجام عملیات ارسال داده
                    LstGetInfo.Items.Clear();
                }
                else if (btnPortState.Text == "قطع ارتباط با دستگاه")
                {
                    btnPortState.Text = "ارتباط با دستگاه";
                    ComPort.Close();
                }
            }
            catch
            {
                btnPortState.Text = "ارتباط با دستگاه";
                ComPort.Close();
                MessageBox.Show("خطا در انجام عملیات");
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if(LstGetInfo.Items.Count <= 0) return;
            int ItemCount = int.Parse(LstGetInfo.Items[0].ToString());
            int ItemIDCount = 0;
            int ItemID = 0;
            int ItemValue1 = 0, ItemValue2 = 0;
            TblIDTableAdapter tblid = new TblIDTableAdapter();
            TblID_DetailsTableAdapter tblid_details = new TblID_DetailsTableAdapter();
            tblid.DeleteAllID();
            LstGetInfo.Items.RemoveAt(0);
            for (int i = 0; i < ItemCount; i++)
            {
                ItemID = int.Parse(LstGetInfo.Items[0].ToString());
                LstGetInfo.Items.RemoveAt(0);
                tblid.Insert(ItemID);
                if (LstGetInfo.Items.Count > 0)
                {
                    ItemIDCount = int.Parse(LstGetInfo.Items[0].ToString());
                    LstGetInfo.Items.RemoveAt(0);
                    for (int j = 0; j < ItemIDCount; j += 2)
                    {
                        ItemValue1 = int.Parse(LstGetInfo.Items[0].ToString());
                        LstGetInfo.Items.RemoveAt(0);
                        ItemValue2 = int.Parse(LstGetInfo.Items[0].ToString());
                        LstGetInfo.Items.RemoveAt(0);
                        tblid_details.Insert(ItemID, calculate_input(ItemValue1, ItemValue2));
                    }
                }
            }
            GetAllIDInDB();
        }

        private void CmbID_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetAllID_DetailsInDB(int.Parse(CmbID.Text));
            if (LstItems.Items.Count > 0)
                ShowChart();
        }

        private void CmbPalette_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            chart1.Palette = (ChartColorPalette)CmbPalette.SelectedIndex;
        }

        private void CmbChartType_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            series.ChartType = (SeriesChartType)CmbChartType.SelectedIndex;
        }
        private void ShowChart()
        {
            CountData = LstItems.Items.Count;
            Values = new double[CountData];
            for (int i = 0; i < CountData; i++)
                Values[i] = double.Parse(LstItems.Items[i].ToString());
            chart1.Titles.Clear();
            chart1.Titles.Add(TxtTitle.Text);
            chart1.Series.Clear();
            series.Points.Clear();
            int Step = 0;
            for (int i = 0; i < CountData; i++, Step +=10)
                series.Points.AddXY(TxtTitleSeries.Text + " " + Step.ToString(), Values[i]);
            chart1.Series.Add(series);
        }

        private void button3_Click_3(object sender, EventArgs e)
        {
            GetAllIDInDB();
        }
    }
}

在本节中,visual studio会出现一个错误,我无法理解它发生了什么

    if (InputData != 0)
    {
     s= Convert.ToString(Convert.ToChar(InputData));

        this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
     label12.Text =Convert.ToString(s);
    }
}

任何人都有这个问题吗?

错误:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll 
Additional information: Cross-thread operation not valid: Control 'label12' accessed from a thread other than the thread it was created on

1 个答案:

答案 0 :(得分:1)

现有的大多数图形用户界面(GUI)框架都是单线程的。这意味着它们只在自己的线程中传递事件,并且只能从它们自己的线程中调用它们。对于您似乎正在使用的WinForms也适用。

您收到的异常是告诉您,您试图从不是GUI线程的线程调用您的GUI(您试图访问控件&#34; label12&#34;)。

所以,要克服你的问题,要么

  • 重构代码,以免您尝试从其他线程访问控件,或

  • 使用Control.Invoke这是为安全地调用其他线程的控件而提供的少数方法之一。更多信息请访问:MSDN - Control.Invoke