如何在C#中使用SerialPort的dataReceived事件

时间:2019-01-09 12:09:54

标签: c# serial-port balance

我有一个应用程序,可以从串行端口c#检索EXA品牌的数据。 我想做同样的事情,但是这次是另一个品牌,KERN PFB,问题是SerialDataReceivedEventHandler事件从不执行。我不知道我在这里想念的是什么。

我尝试过:How do I use dataReceived event of the SerialPort Port Object in C#?

    public static  SerialPort mySerialPort = new SerialPort("COM1");
    public static string indata = string.Empty;

    public static void SetSetting()
    {
        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.RtsEnable = true;

        mySerialPort.DataReceived += MySerialPort_DataReceived;
    }

    public static void MySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        indata += sp.ReadExisting();
    }

    public static float GetPesage()
    {
        indata = string.Empty;
        mySerialPort.Open();
        Thread.Sleep(1000);

        string[] dataSplited = indata.Trim().Split(' ');            
        float poids = 0;
        //
        ...
        //

        mySerialPort.Close();
        return poids;
    }

我希望已收到数据,但没有收到。

谢谢。

1 个答案:

答案 0 :(得分:0)

 Command S : Stable weighing value for the weight is sent via the interface
public static float GetPesage()
{
    indata = string.Empty;
    mySerialPort.Open();
    mySerialPort.Write("s");
    Thread.Sleep(1000);
    string[] dataSplited = indata.Trim().Split(' ');            
    float poids = 0;
    //
    ...
    //
    mySerialPort.Close();
    return poids;
}