2017-09-14 44 views
0

我正在使用Visual Studio 2015並使用C#進行編碼。從串行端口獲取數據並在Datetime中使用設置時間c#​​

我在我的pic32上編寫了一個時鐘,並通過串口發送了此時鐘的數據。

我試圖從串口把一個字符串mydata放進日期時間。但我得到的豁免,不知道爲什麼。

什麼,我讓我的myData的我是這樣的:00:10:2300:10:2300:10:2300:10:2300:10:2300:10:2300:10:23

莫非你們給我一個關於這個?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.IO.Ports; 
using System.Diagnostics; 

namespace klokske 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 

      if (!mySerialPort.IsOpen) 
      { 
       mySerialPort.Open(); 
       rtRX.Text = "Port Opened"; 
      } 
      else 
       rtRX.Text = "Port busy"; 
     } 

     DateTime dateTime; 

     private void AnalogClock_Load(object sender, System.EventArgs e) 
     { 
      dateTime = DateTime.Parse(myData); 
     } 

       private string myData; 
     private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) 
     { 
       myData = mySerialPort.ReadExisting(); 
       this.Invoke(new EventHandler(displayText)); 
     } 

     private void displayText(object o, EventArgs e) 
     { 
      rtRX.AppendText(myData); 
     } 
    } 
} 
+0

請提供一個[mcve](**不**所有的代碼)並且詢問**特定的**問題。目前,很難說你實際上在問什麼。你的具體問題在哪裏? – dymanoid

+0

也許使用[DateTime.ParseExact](https://msdn.microsoft.com/en-us/library/w2sa9yss(v = vs.110).aspx)? – Fildor

+2

幾乎沒有人瞭解ReadExisting()如何工作。這很奇怪,它確實有一個很好的名字。它返回接收緩衝區中的* exists *。這絕對不是「00:10:23」。您通常會得到一個或兩個字符,串行端口很慢。計數它們是必需的,最好用Read()完成。 –

回答

0

由於@Hans帕桑特提到的,ReadExisting()只返回什麼是目前在接收緩衝區。 DataReceived事件可以隨機觸發,所以當這個事件觸發時,你可能沒有找到你正在查找的所有角色。你需要建立一個字符串,直到你有完整的消息,然後你可以顯示文本。

char ESC = (char)27; 
char CR = (char)13; 
char LF = (char)10; 
StringBuilder sb = new StringBuilder(); 

//in my case, the data im expected is ended with a Line Feed (LF) 
//so I'll key on LF before I send my message 
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 
{ 
    string Data = serialPort1.ReadExisting(); 

    foreach (char c in Data) 
    { 
     if (c == LF) 
     { 
      sb.Append(c); 

      this.Invoke(new EventHandler(sb.toString())); 
     } 
     else 
     { 
      //else, we append the char to our string that we are building 
      sb.Append(c); 
     } 
    } 
}