你好
我在C#串口中是新的。我正在编写一个运行winXP和win7的C#程序,以在发送机器数据时保留从串行端口接收的数据。

using System.IO;
using System.IO.Ports;
using System.Threading;


namespace RS232RVR
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        SettingRS232();
    }

    public void SettingRS232 ()
    {
        try
        {
            SerialPort mySerialPort = new SerialPort("COM6");

            mySerialPort.BaudRate = 9600;
            mySerialPort.Parity = Parity.None;
            mySerialPort.StopBits = StopBits.One;
            mySerialPort.DataBits = 8;
            mySerialPort.Handshake = Handshake.None; //send to hardware flow control.

            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceviedHandler);

            mySerialPort.Open();


            richTextBox1.Text = "on";

            mySerialPort.Close();
        }
        catch (Exception ex)
        {
            richTextBox1.Text = ex.Message;
        }

    }

    private void DataReceviedHandler(
                    object sender,
                    SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        richTextBox1.Text = indata;

    }

}

}

COM6在我的电脑中处于 Activity 状态。但是我的问题是,当数据接收到来自串行端口的数据时,似乎不会触发datareceived事件。 (我已经通过使用一些免费软件应用程序检查了这项运动)

有人可以帮忙吗?

谢谢

最佳答案

        mySerialPort.Open();
        richTextBox1.Text = "on";
        mySerialPort.Close();

那是行不通的,您将在打开串行端口后几秒钟将其关闭。是的,DataReceived事件处理程序不太可能触发。仅在关闭程序时关闭端口。
        mySerialPort.Handshake = Handshake.None

这也是一个问题,您现在需要自己控制握手信号。绝大多数串行端口设备在看到机器启动并准备好接收之前,不会发送任何内容。将DtrEnabled和RtsEnabled属性设置为true。

关于c# - RS232串口通信C#Win7 .NET Framework 3.5 SP1,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5101217/

10-09 16:57