串行端口连接,Readline / ReadExisting不起作用

时间:2013-04-02 08:05:54

标签: c# serial-port

我正在尝试与另一台机器建立串行连接。我正在使用虚拟串行端口仿真器来试试这个。我在超级终端上使用的设置如下所示。我可以看到portopen是true,但我无法检查我是否可以写或读。当我尝试ReadLine方法时,它会给出TimeoutException,当它是readExisting命令时,它什么都不做。永远不会触发DataReceived。你可以帮帮我吗?

 private void Page1_Load(object sender, EventArgs e)
        {

        //Port name can be identified by checking the ports


        // section in Device Manager after connecting your device
        serialPort1.PortName = "COM14"; // that one works for me

        //Provide the name of port to which device is connected

        //default values of hardware[check with device specification document]
        serialPort1.BaudRate = 115200;
        serialPort1.Parity = Parity.None;
        serialPort1.DataBits = 8;
        serialPort1.StopBits = StopBits.One;
        serialPort1.Handshake = Handshake.None;
        serialPort1.RtsEnable = true;
        serialPort1.DtrEnable = true;
        serialPort1.ReceivedBytesThreshold = 8;
        serialPort1.ReadTimeout = 2000;
        serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);  //
        // Writes data to the Serial Port output buffer 

        //opens the port
        serialPort1.Open();
    }

      private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {


        inputData = serialPort1.ReadExisting();
        this.Invoke((MethodInvoker)delegate { DoUpdate(); });


    }

     public void DoUpdate()
    {
        textOutput.Text = (textOutput.Text + inputData);

    }

     private void btnReadExist_Click(object sender, EventArgs e)
    {

        if ((serialPort1.IsOpen == true))
        {


           serialPort1.WriteLine("something"); 
           string read= serialPort1.ReadExisting();
           //string output = serialPort1.ReadLine();
           textOutput.Text += read;

        }
    }


    private void Page1_FormClosed(object sender,System.Windows.Forms.FormClosedEventArgs e)
    {
        //  Close the Serial Port
          serialPort1.Close();
    }

1 个答案:

答案 0 :(得分:0)

问题似乎是你正在阅读两个代码块:首先,直接在按钮事件中发送文本后。其次,您指定了一个事件,在异步调用时读取数据。您应该决定使用哪一个并删除另一个。