1. 程式人生 > 實用技巧 >C# 串列埠通訊的基本用法

C# 串列埠通訊的基本用法

一、串列埠通訊

串列埠通訊(Serial Communications),即串列埠按位(bit)傳送和接收位元組。

儘管比按位元組(byte)的並行通訊慢,但是串列埠可以在使用一根線傳送資料的同時用另一根線接收資料。

串列埠通訊最重要的引數是波特率、資料位、停止位和奇偶校驗。對於兩個進行通訊的埠,這些引數必須匹配。

1.波特率:這是一個衡量符號傳輸速率的引數。

指的是訊號被調製以後在單位時間內的變化,即單位時間內載波引數變化的次數,如每秒鐘傳送960個字元,

而每個字元格式包含10位(1個起始位,1個停止位,8個數據位),這時的波特率為960Bd,位元率為10位*960個/秒=9600bps。

2.資料位這是衡量通訊中實際資料位的引數。

當計算機發送一個資訊包,實際的資料往往不會是8位的,標準的值是6、7和8位。

標準的ASCII碼是0~127(7位),擴充套件的ASCII碼是0~255(8位)。

3.停止位:用於表示單個包的最後幾位。典型的值為1,1.5和2位。

由於資料是在傳輸線上定時的,並且每一個裝置有其自己的時鐘,很可能在通訊中兩臺裝置間出現了小小的不同步。

因此停止位不僅僅是表示傳輸的結束,並且提供計算機校正時鐘同步的機會。

4.校驗位:在串列埠通訊中一種簡單的檢錯方式。

有四種檢錯方式:偶、奇、高和低。當然沒有校驗位也是可以的。

二、基本功能用法

1.首先需要獲取一些資料,必須要有的。

1     public static
string portName; //串列埠號 2 public static int baudRate; //波特率 3 public static Parity parity; //校驗位 4 public static int dataBit; //資料位 5 public static StopBits stopBit; //停止位

2.就需要連線串列埠

 1     /// <summary>
 2     /// 開啟埠
 3     /// </summary>
 4     public static void OpenPort()
5 { 6 sp = new SerialPort(portName, baudRate, parity, dataBit, stopBit); 7 sp.ReadTimeout = 1000; 8 try 9 { 10 sp.Open(); 11 Debug.Log("開啟埠成功"); 12 } 13 catch (Exception e) 14 { 15 Debug.Log(e.Message); 16 } 17 }

3.連線成功後,就需要互動了

1     /// <summary>
2     /// 傳送資料
3     /// </summary>
4     /// <param name="dataStr"></param>
5     public static void SendData(byte[] dataStr)
6     {
7         sp.Write(dataStr, 0, dataStr.Length);
8         Debug.LogWarning("傳送成功");
9     }
 1    /// <summary>
 2     /// 接收埠資料
 3     /// </summary>
 4     public void DataReceiveFun()
 5     {
 6         while (true)
 7         {
 8             if (sp != null && sp.IsOpen)
 9             {
10                 try
11                 {
12                     bytes = sp.Read(buffer, 0, buffer.Length);
13                     sp.DiscardOutBuffer();
14                     if (bytes == 0)
15                     {
16                         continue;
17                     }
18                     else
19                     {
20                         for (int i = 0; i < buffer.Length; i++)
21                         {
22                             Debug.Log(buffer[i].ToString("x8"));
23                         }
24                     }
25                 }
26                 catch (Exception e)
27                 {
28                     Debug.Log(e);
29                 }
30             }
31             Thread.Sleep(500);
32         }
33     }

三、其他便捷功能

1.串列埠的訊息進位制轉換

 1 //十進位制轉二進位制
 2 Console.WriteLine(Convert.ToString(69, 2));
 3 
 4 //十進位制轉八進位制
 5 Console.WriteLine(Convert.ToString(69, 8));
 6 
 7 //十進位制轉十六進位制
 8 Console.WriteLine(Convert.ToString(69, 16));
 9 
10 //二進位制轉十進位制
11 Console.WriteLine(Convert.ToInt32("100111101", 2));
12 
13 //八進位制轉十進位制
14 Console.WriteLine(Convert.ToInt32("76", 8));
15 
16 //16進位制轉換10進位制
17 Console.WriteLine(Convert.ToInt32("FF", 16));

2.訊息資訊流轉換

 1     /// <summary>
 2     /// 字串轉位元組流
 3     /// </summary>
 4     /// <param name="hexStr"></param>
 5     /// <returns></returns>
 6     public static byte[] HexStringToBytes(string hexStr)
 7     {
 8         if (string.IsNullOrEmpty(hexStr))
 9         {
10             return new byte[0];
11         }
12 
13         if (hexStr.StartsWith("0x"))
14         {
15             hexStr = hexStr.Remove(0, 2);
16         }
17 
18         var count = hexStr.Length;
19 
20         var byteCount = count / 2;
21         var result = new byte[byteCount];
22         for (int ii = 0; ii < byteCount; ++ii)
23         {
24             var tempBytes = Byte.Parse(hexStr.Substring(2 * ii, 2), System.Globalization.NumberStyles.HexNumber);
25             result[ii] = tempBytes;
26         }
27 
28         return result;
29     }
 1     /// <summary>
 2     /// 位元組流轉字串
 3     /// </summary>
 4     /// <param name="bytes"></param>
 5     /// <returns></returns>
 6     public static string BytesTohexString(byte[] bytes)
 7     {
 8         if (bytes == null || bytes.Length < 1)
 9         {
10             return string.Empty;
11         }
12 
13         var count = bytes.Length;
14 
15         var cache = new StringBuilder();
16         cache.Append("0x");
17         for (int ii = 0; ii < count; ++ii)
18         {
19             var tempHex = Convert.ToString(bytes[ii], 16).ToUpper();
20             cache.Append(tempHex.Length == 1 ? "0" + tempHex : tempHex);
21         }
22 
23         return cache.ToString();
24     }

*** | 以上內容僅為學習參考、學習筆記使用 | ***