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     }

*** |  以上内容仅为学习参考、学习笔记使用  | ***

原文地址:https://www.cnblogs.com/ChenZiRong1999/p/13672597.html