如何在循环中收回所有数据?

时间:2016-02-23 14:17:04

标签: c# arrays loops for-loop serial-port

我编写了一个C#代码,它将函数(1-9)发送到微控制器,控制器将通过RS232(SERIAL PORT)将数据发送回我的计算机。我唯一的问题是我希望通过发送功能(1-9)并自动从控制器接收它来实现自动化。通过这样做,我使用了for循环,但它只显示从上一个函数发送的数据,函数9。但是,我希望它显示所有数据接收。如何显示控制器发回的所有收到的数据?有什么建议吗?

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;
using System.Timers;
using System.IO;
using System.Net;
using System.Threading;

namespace SMCData
{
public partial class Form1 : Form
{

    SerialPort _serialPort = new SerialPort();

    public Form1()
    {
        InitializeComponent();
        _serialPort.DataReceived += new SerialDataReceivedEventHandler(DataRecivedHandler);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (string s in SerialPort.GetPortNames())
        {
            comport.Items.Add(s);
        }
    }

    // settup connection 
    void setport()
    {
        //checking if Baud_Rate_txt is blank
        string temp1 = Baud_Rate_txt.Text;

        if (temp1 == "")
        {
            _serialPort.BaudRate = 9600;
        }
        else
        {
            _serialPort.BaudRate = int.Parse(Baud_Rate_txt.Text);
        }


        /* if (comport.SelectedIndex == -1)
         {
            ErrorBox.Text = " Need Com Port name";
             return;
         } */
        _serialPort.PortName = comport.Text;//comport.SelectedItem.ToString();
        _serialPort.DataBits = 8;
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;
        _serialPort.RtsEnable = true;
        _serialPort.DtrEnable = true;
        switch (HandshakeCB.Text)
        {
            case "None":

                _serialPort.Handshake = Handshake.None;
                break;
            case "XOnXOff":
                _serialPort.DtrEnable = true;
                _serialPort.Handshake = Handshake.XOnXOff;
                break;
        }
        switch (Parity_CB.Text)
        {
            case "None":
                _serialPort.Parity = Parity.None;
                break;
            case "Even":
                _serialPort.Parity = Parity.Even;
                break;
            case "Odd":
                _serialPort.Parity = Parity.Odd;
                break;
        }
        // Looks for user input on the desired Stop Bits of Application
        switch (StopBitsCB.Text)
        {
            case "1":
                _serialPort.StopBits = StopBits.One;
                break;
            case "2":
                _serialPort.StopBits = StopBits.Two;
                break;
            case "None":
                _serialPort.StopBits = StopBits.None;
                break;
        }
        try
        {
            _serialPort.Open();


        }
        catch (UnauthorizedAccessException ex)
        {
            errorbox.Text = ex.Message + System.Environment.NewLine;
        }

    }
    //Data Receive Fucntion
    private void DataRecivedHandler(object sender, SerialDataReceivedEventArgs e)
    {

            SerialPort sp = (SerialPort)sender;
         int temp2;
        string data;
     int temp =sp.BytesToRead;
     byte[] array = new byte[temp];
     temp2 = sp.Read(array, 0, temp);
          if (this.DataRecived.InvokeRequired) 
          {
              DataRecived.BeginInvoke((Action)(() =>
                  {
                      data =  Encoding.Default.GetString(array) ;


                      processdata(data);
                      DataRecived.Text = DataRecived.Text + data + System.Environment.NewLine;



                  }));
          }

    }

    private void Dispose(RichTextBox dataRecived)
    {
        throw new NotImplementedException();
    }

    private void sendBLN_Click(object sender, EventArgs e)
      {

        // byte[] array_out = Encoding.ASCII.GetBytes(SendTXT.Text);

        //_serialPort.Write(array_out, 0, array_out.Length);

        // byte[] array_out2 = new byte[1];
        //array_out2[0] = 0xD; //Encoding.ASCII.GetBytes("\r");
        //  byte[] array_out3 = { 141 };

        //_serialPort.Write(array_out2, 0, array_out2.Length);
        //  _serialPort.Write(array_out3, 0, array_out3.Length);


        //automate the process by sending 1,2,3,etc


        for (int i = 0; i < 10; i++)

        {

            string c = Convert.ToString(i);

            byte[] array_out = Encoding.ASCII.GetBytes(c); //convert i to the right variable type;
                _serialPort.Write(array_out, 0, array_out.Length);
                byte[] array_out2 = new byte[1];
                array_out2[0] = 0xD;

            _serialPort.Write(array_out2, 0, array_out2.Length);

            //print what you receive

            }



    }

    private void Refresh_btn_Click(object sender, EventArgs e)
      {
          foreach (string s in SerialPort.GetPortNames())
          {
              comport.Items.Remove(s);
          }

          foreach (string s in SerialPort.GetPortNames())
          {
              comport.Items.Add(s);
          }
      }

      private void Connectbtn_Click(object sender, EventArgs e)
      {
          try
        {
            if (!_serialPort.IsOpen)
                errorbox.Text = errorbox.Text + "Connected..." + System.Environment.NewLine;
            setport();

        }
          catch (Exception ex )
          {
            errorbox.Text = errorbox.Text + ex.Message + System.Environment.NewLine;
        }
      }

    private void button1_Click(object sender, EventArgs e)
    {

    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        _serialPort.Close();
        errorbox.Text = " Disconnect";
    }

    private void button2_Click(object sender, EventArgs e)
    {
        DataRecived.Text = " ";
        errorbox.Text = " ";

    }

    private void DataRecived_TextChanged(object sender, EventArgs e)
    {

    }

    void processdata(string data)
    {
        if (data.Contains("No  Action") == true)
        {
            return;
        }
        else if (data.Contains("Array Volt") == true)
        {
         string[] temp =  data.Split('=');
            temp[1].Trim('\r');

        }


    }

    private void button3_Click(object sender, EventArgs e)
    {

        byte[] array_out2 = new byte[1];
        array_out2 = Encoding.ASCII.GetBytes("\r");

        _serialPort.Write(array_out2, 0, array_out2.Length);


    }

    private void SendTXT_TextChanged(object sender, EventArgs e)
    {

    }

    private void comport_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}

}

0 个答案:

没有答案