如何从串口获得重量?

时间:2012-07-10 15:07:50

标签: c# serial-port

我有一个WPF应用程序,它有一个用于称量负载的模块。由于串口通信因地磅而异,我想将称重模块作为单独的dll。

我正在创建一个类库,我使用串口来称量负载。我需要将重量还给主程序。

double GetWeights()
{

 spWeigh = new SerialPort("COM1", 2400, Parity.None, 8, StopBits.One);
            spWeigh.RtsEnable = false;
            spWeigh.DtrEnable = false;
            spWeigh.Handshake = Handshake.None;
            spWeigh.ReadTimeout = 10000;
            spWeigh.DataReceived +=spWeigh_DataReceived;

}

但收到的数据是一个不同的主题。我如何在主程序中获得重量?

 void spWeigh_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
      // code here
    }

2 个答案:

答案 0 :(得分:1)

您是否可以向您的主程序订阅的库添加一个事件,哪些事件由您的库引发,并传回所需的数据?

在你的图书馆:

class YourLibrary
{
    public delegate void RawDataEventHandler(object sender, RawDataEventArgs e);
    public event RawDataEventHandler RawDataReceived;

    void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string ReceivedData = _serialPort.ReadExisting();
        if (RawDataReceived != null)
            RawDataReceived(this, new RawDataEventArgs(ReceivedData));
    }
}

class RawDataEventArgs : EventArgs
{
    public string Data { private set; get; }

    public RawDataEventArgs(string data)
    {
        Data = data;
    }
}

在您的主程序中:

class MainProgram
{
    YourLibrary library = new YourLibrary();
    library.RawDataReceived += new YourLibrary.RawDataEventHandler(library_RawDataReceived);

    void library_RawDataReceived(object sender, RawDataEventArgs e)
    {
        // Your code here - the data passed back is in e.Data
    }
}

答案 1 :(得分:0)

如果数据不需要很快(即每秒少于一次),您可以在一个线程中写入文本文件并在主线程中从中读取