C#學習【 串口學習】

簡單的說幾句:打算記錄做項目時遇到的問題,以便以後少走彎路。工程中經常會用到串口通信,一般就是PC與某個設備間的通信,即PC端按照某種特定的格式(稱爲協議),往設備發數據,設備接收到數據後返回給PC一個字符串。最近再看《解密》,類似一種加密解密過程。


串口使用很像讀寫文件,MFC中就是使用ReadFile和WriteFile 來讀寫串口的,串口使用的大致流程  打開串口  -> 發送數據  ->接收數據   ->關閉串口


C#中已經封裝好了該接口,調用起來很方便。

微軟官方文檔


1.打開串口

        //初始化串口
        public void Init(XXXXXXFrom from, string commName = "COM3", int commBaudRate = 115200, int commDataBits = 8)
        {
            this.parentFrom = from;//用於輸出LOG到的界面

            this.commForDtu = new System.IO.Ports.SerialPort();
            this.builder = new StringBuilder();//避免在事件處理方法中反覆的創建,定義到外面。 

            //串口配置
            this.commForDtu.PortName = commName;
            this.commForDtu.BaudRate = commBaudRate;
            this.commForDtu.DataBits = commDataBits;

            try
            {
                this.AddLog("打開串口...");//自己封裝一個this.parentFrom.AddLog(strLog);

                this.commForDtu.Open();//打開串口
            }
            catch (System.Exception ex)
            {
                this.AddLog(String.Format("打開串口失敗!錯誤爲【{0}】",ex.Message));
            }

            //添加數據接收事件
            this.commForDtu.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.OnDataReceived);
        }
2.發送數據
        public  void SendMessage(string strData)
        {
            if (String.IsNullOrEmpty(strData)) return;

            try
            {
                this.AddLog("發送串口數據...");

                byte[] bs = Encoding.ASCII.GetBytes(strData);
                this.commForDtu.Write(bs,0, bs.Length);//發送數據
            }
            catch (Exception ex)
            {
                //發送數據失敗
                this.AddLog(String.Format("發送串口數據失敗!錯誤爲{0}", ex.Message));
            }
        }


3.接收數據

          private void OnDataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
          {
              try
              {
                  int n = this.commForDtu.BytesToRead;
                  byte[] buf = new byte[n];//聲明一個臨時數組存儲當前來的串口數據      

                  this.commForDtu.Read(buf, 0, n);//讀取緩衝數據
                  this.builder.Clear();//清除字符串構造器的內容

                  builder.Append(Encoding.ASCII.GetChars(buf));

                  //接收到數據
                  {
                      this.AddLog(builder.ToString());
                      if (builder.ToString() == Constants.ServerNeedNewData)
                      {
                          //發送最新數據
                      }
                  }
              }
              catch (Exception ex)
              {
                  //接收數據失敗
                  this.AddLog(String.Format("讀取串口數據失敗!錯誤爲{0}", ex.Message));
              }
         
          }

項目中遇到過的問題

1. 串口通常是PC端串口(就是串口的小孔和針)的235 接設備的235,有的設備搞特殊,內部將23對調,如果不換線的的話 就變成了,數據可能就發不過去了

2. 串口發送接收數據可能不穩,尤其是溫度比較高或者震動比較的環境,有一款可以增強串口穩定性的(忘了不知道叫什麼了),可以實現串口數據的穩定

3. 之前做MFC時,串口數據可能不是一個包發過來 例如 設備發過來5201314,可能需要讀取兩次 第一次爲520131,第二次爲4,所以做法就是一直讀到7個字節再處理,不知道C#有沒有這樣的問題

待添加。。。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章