读取带有C#的串行端口时出错

本文关键字:串行端口 出错 读取 | 更新日期: 2023-09-27 18:21:21

我有一个系统,它在所有串行端口上进行循环,并为它们发送命令"at"。这些端口在Putty中返回"ok",但在C#中MessageBox为空。为什么会发生这种情况?

腻子:https://i.stack.imgur.com/6cbfk.png/C#:https://i.stack.imgur.com/soJc7.png

public partial class Form1 : Form
        {
            List<SerialPort> serialPort = new List<SerialPort>();
            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, 9600, 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_1(object sender, EventArgs e)
            {
                foreach (var sp in serialPort)
                {
                    // Open port
                    try
                    {
                        if (!sp.IsOpen)
                            sp.Open();
                        sp.Write("at'r'n");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");
                    }
                }
            }
            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 });
            }
            private void si_DataReceived(string data)
            {
                String retorno = data.Trim();
                MessageBox.Show(data);
            }
    }

读取带有C#的串行端口时出错

您的调制解调器响应如下:''n''rOK ''n''r您应该读取缓冲区中的所有流,或者您应该使用ReadLine()方法读取3倍串行端口缓冲区。