2

我有一个向串行端口发送“at”命令并在 MessageBox 上显示返回的系统。但我需要在所有可用的串行端口中执行此操作。所以我创建了一个列表,并在上面添加了所有端口。我设法发送了命令,但无法继续其余代码来捕获返回,因为我在处理列表时遇到了麻烦。我是 C# 的初学者。以下是我当前的代码。被注释掉的部分是我正在努力继续的部分。这部分属于旧代码(当时只是一个串口)。

public partial class Form1 : Form
    {
        List<SerialPort> serialPort = new List<SerialPort>();

        // delegate is used to write to a UI control from a non-UI thread
        private delegate void SetTextDeleg(string text);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var portNames = SerialPort.GetPortNames();
            foreach (var port in portNames) {
                SerialPort sp;
                sp = new SerialPort(port, 19200, Parity.None, 8, StopBits.One);
                sp.Handshake = Handshake.None;
                //sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
                sp.ReadTimeout = 500;
                sp.WriteTimeout = 500;

                serialPort.Add(sp);
                listPorts.Items.Add(port);
            }
        }

        private void listPorts_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (var sp in serialPort) {
                // Open port
                try
                {
                    if (!sp.IsOpen)
                        sp.Open();

                    MessageBox.Show(sp.PortName + " aberto!");
                    sp.Write("at\r\n");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");
                }
            }
        }

        /* HELP START

        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(500);
            string data = sp.ReadLine();
            this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
        }

        private void si_DataReceived(string data)
        {
            String retorno = data.Trim();
            MessageBox.Show(retorno);
            // Fecha a porta após pegar o retorno
            sp.Close();
        }

        HELP END */

    }

放置什么'sp.ReadLine();' 和'sp.Close();'?我不知道这样做是因为 List <>

4

3 回答 3

3

最简单的方法是使用lambda 表达式来捕获您正在使用的端口。lambda 表达式是一种构建委托“内联”的方式 - 并且能够使用您在其中声明它的方法中的局部变量。

例如:

foreach (var port in portNames)
{
    // Object initializer to simplify setting properties
    SerialPort sp = new SerialPort(port, 19200, Parity.None, 8, StopBits.One)
    {
        Handshake = Hanshake.None,
        ReadTimeout = 500,
        WriteTimeout = 500
    };
    sp.DataReceived += (sender, args) =>
    {
        Thread.Sleep(500); // Not sure you need this...
        string data = sp.ReadLine();
        Action action = () => {
            MessageBox.Show(data.Trim());
            sp.Close();
        };
        BeginInvoke(action);
    };
    serialPort.Add(sp);
    listPorts.Items.Add(port);
}

关于这一点的几点说明:

  • 仅仅因为收到了一些数据并不意味着整行都有,所以ReadLine仍然可能阻塞
  • 如果你需要显示一个消息框,你可能不需要Control.BeginInvoke. (如果您需要在这里做更多的事情,您可能希望将大部分代码提取到一个单独的方法中,该方法只接受一个字符串,然后创建一个调用该方法的操作。)
  • 您确定要在收到第一行后立即关闭串行端口吗?
于 2013-07-08T06:01:59.570 回答
1

你可以改变你的sp_DataReceived方法,

       void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(500);
            SerialPort sp = (SerialPort)sender;
            string data = sp.ReadLine();
            this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
            sp.Close();
        }

并删除sp.Close();fromsi_DataReceived方法。

于 2013-07-08T06:06:52.223 回答
0

如果你想在你的 si_DataReceived 方法中有一个串口值,你应该把它传递到那里:

  // First, add port into your delegate
  private delegate void SetTextDeleg(SerialPort port, string text);
  ...
  /* HELP START */

  void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
  {
    Thread.Sleep(500);
    SerialPort sp = (SerialPort) sender; // <- Obtain the serial port
    string data = sp.ReadLine();

    // Pass the serial port into  si_DataReceived: SetTextDeleg(sp, ...
    this.BeginInvoke(new SetTextDeleg(sp, si_DataReceived), new object[] { data }); 
  }

  // "SerialPort sp" is added
  private void si_DataReceived(SerialPort sp, string data) {
    String retorno = data.Trim();
    MessageBox.Show(retorno);
    // Fecha a porta após pegar o retorno
    sp.Close();
  }

  /* HELP END */

也可以看看:

http://msdn.microsoft.com/library/system.io.ports.serialport.datareceived.aspx

于 2013-07-08T06:15:44.870 回答