使用C#读取串口时出错

时间:2013-07-08 07:24:01

标签: c# .net serial-port

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

Putty:http://i.imgur.com/AZY7aRY.png / C#:http://i.imgur.com/wgGyT2x.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);
            }
    }

1 个答案:

答案 0 :(得分:1)

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