2016-10-08 70 views
0

我試圖爲稱重橋架製作軟件,同時嘗試讀取使用C#代碼,它顯示類似下面如何使用C#

 
)0 12589 00 
)0 12589 00 
)0 12589 00 
)0 12589 00 
)0 12589 00 
)0 12589 00 
private void timer1_Tick(object sender, EventArgs e) 
{ 
    string Port = GenDbUtility.GetElixirConfigValue("SERIAL_PORT", Globals.CompCode); 

    //<-- This block ensures that no exceptions happen 
    if (serialPort1 != null && serialPort1.IsOpen) 
     serialPort1.Close(); 
    if (serialPort1 != null) 
     serialPort1.Dispose(); 
    //<-- End of Block 


    serialPort1 = new SerialPort("COM1");  //<-- Creates new SerialPort using the name selected in the combobox 
    serialPort1.Encoding = Encoding.ASCII; 
    serialPort1.BaudRate = 9660; 
    serialPort1.Parity = Parity.None; 
    serialPort1.StopBits = StopBits.One; 
    serialPort1.DataBits = 50; 
    serialPort1.Handshake = Handshake.None; 
    serialPort1.RtsEnable = true; 
    serialPort1.ReadBufferSize = 4096; 
    serialPort1.ReceivedBytesThreshold = 100000; 
    serialPort1.NewLine = "\r\n"; 
    serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); 
    serialPort1.Open();  //<-- make the comport listen 
} 

void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) 
{ 
    if (serialPort1.IsOpen) 
    { 
     SerialPort sp = (SerialPort)sender; 

     string newVal = sp.ReadExisting().ToString(); 
     ///string[] qty = newVal.Split(' '); 
     //txtQuantity.Invoke(this.myDelegate, new Object[] { qty[3].ToString() }); 
     //string[] qty = newVal.Split(' '); 
     //decimal Quantity1 = Convert.ToDecimal(qty[0]); 
     //decimal Quantity2 = Convert.ToDecimal(qty[1]); 
     //decimal Quantity3 = Convert.ToDecimal(qty[2]); 
     //decimal Quantity4 = Convert.ToDecimal(qty[3]); 
     //txtQuantity.Text = Quantity3.ToString(); 

     //if (String.Compare(txtQuantity.Text, qty[3]) != 0) 
     //{ 
     // txtQuantity.Text = Convert.ToString(qty[3]); 
     // //lblweight.Text = Convert.ToString(qty[2]); 
     //  //qty[2].ToString(); 
     //} 
    } 
} 
+0

你正在閱讀的數據包中的每個字節應該是有意義的。閱讀他們的意思文檔。並非全部都是數據。 – Ogbe

+0

可能會嘗試使用工具來讀出COM端口以將結果與您收到的結果進行比較。可能適應COM端口的項目會返回錯誤的數據。 – Oswald

+0

嘗試像MSDN(https://msdn.microsoft.com/en-us/library/system.io.ports.serialport(v=vs.110).aspx)中的示例一樣實現串行端口讀取器有一個完整的示例你可以使用的課程。 – Oswald

回答

1
一些其他的數據進行處理的數據讀取系統的串口數據

串口不知道「消息」有多長。您正在閱讀的設備將發佈某種形式的協議,您需要遵循以閱讀正確的數據。

你不能假設sp.ReadExisting()將數據正好一個消息值得的,它可能有不到一個完整的消息,並可以結合兩個消息的若干部分,並返回它作爲一個結果(這是你所遇到的問題) 。去閱讀稱重橋的文件,只讀出你應該讀出的部分。

-1

com端口可以像驅動器一樣打開,即COM1:而不是例如。 C: 我沒有足夠的C#知道文件系統的功能,但是在C/C++中它的fopen()等

+0

這與OP的問題無關。他可以打開com端口,並從中獲取數據。他只是不明白爲什麼他回來的數據不符合他的預期。 –