如何在串口C中调用接收数据#

时间:2014-04-08 18:09:59

标签: c# serial-port

我是C#串口的新手......

我有一个虚拟串口驱动程序并尝试此代码......

 private string strPortData = null;

    private void okButton_Click(object sender, EventArgs e)
    {
                if (!serialPort1.IsOpen)
                {
                    serialPort1.Open();
                }

                string strPortData= "CMD1";

                serialPort1.WriteLine(strPortData);

    }

    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        textBox1.Text = serialPort1.ReadLine();
    }

但不要调用serialPort1_DataReceived。

如何调用DataReceived?

1 个答案:

答案 0 :(得分:2)

尝试创建一个代码类似于以下代码的新控制台应用程序

void Main()
{
    using (SerialPort serialPort1 = new SerialPort("COM1"))
    using (SerialPort serialPort2 = new SerialPort("COM2"))
    {
        serialPort1.DataReceived += (sender, args) => {
            Console.WriteLine("COM1 Received: " + serialPort1.ReadLine());
        };

        serialPort2.DataReceived += (sender, args) => {
            Console.WriteLine("COM2 Received: " + serialPort2.ReadLine());
        };

        serialPort1.Open();
        serialPort2.Open();

        serialPort1.WriteLine("Hello, COM2!");

        Thread.Sleep(200);
    }
}

以上代码打开两个串行端口,设置接收的数据事件,并通过它发送数据。如果你运行该代码,你会看到“COM2收到:你好,COM2!”输出