第一 设置参数:
在打开串口之前,需要设置串口的串口号、波特率、停止位、数据位、校验位。
对应C#代码:SerialPort.PortName
、BaudRate
、StopBits
、DataBits
、Partity
例子:serialP = new SerialPort("COM4", 9600,Parity.None,8,StopBits.One);
第二 打开串口与关闭串口:
serialP.Open();
serialP.Close();
第三 数据的接收与发送
注意:在数据既需要接收也需要发送的时候,我们就会考虑同步的问题,如果需要满足发送与接收同步,就不能使用串口的DataReceive
事件(用于异步接收串口数据事件)。
发送,可以使用SerialPort.Write(byte[] buffer, int offset, int count)
其中count = buffer.Length
//串口的十六进制发送转换函数
sp.Write(HexStringToBytes(TextBox_Sen.Text), 0, HexStringToBytes(TextBox_Sen.Text).Length );
几个常用的自定义十六进制转换函数
//在串口通讯过程中,经常要用到 16进制与字符串、字节数组之间的转换
public static byte[] HexStringToBytes(string hs)
{
string[] strArr = hs.Trim().Split(' ');
byte[] b = new byte[strArr.Length];
//逐个字符变为16进制字节数据
for (int i = 0; i < strArr.Length; i++)
{
b[i] = Convert.ToByte(strArr[i], 16);
}
//按照指定编码将字节数组变为字符串
return b;
}
//十六进制转十进制,需要两个程序块Hex2Ten(string hex)及HexChar2Value(string hexChar)
public static string Hex2Ten(string hex)
{
int ten = 0;
for (int i = 0, j = hex.Length - 1; i < hex.Length; i++)
{
ten += HexChar2Value(hex.Substring(i, 1)) * ((int)Math.Pow(16, j));
j--;
}
return ten.ToString();
}
public static int HexChar2Value(string hexChar)
{
switch (hexChar)
{
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
return Convert.ToInt32(hexChar);
case "a":
case "A":
return 10;
case "b":
case "B":
return 11;
case "c":
case "C":
return 12;
case "d":
case "D":
return 13;
case "e":
case "E":
return 14;
case "f":
case "F":
return 15;
default:
return 0;
}
}
public static string Hex2Asc(string s)//Hex转Ascii
{
string str = s.Replace(" ", "");//去除字符串中的空格
//str十六进制字符串
byte[] buff = new byte[str.Length / 2];
int index = 0;
for (int i = 0; i < str.Length; i += 2)
{
buff[index] = Convert.ToByte(str.Substring(i, 2), 16);
++index;
}
string result = Encoding.Default.GetString(buff);
return result.ToString();
}
文本框仅允许输入特定内容
^[A-Za-z]+$ //匹配由26个英文字母组成的字符串
^[A-Z]+$ //匹配由26个英文字母的大写组成的字符串
^[a-z]+$ //匹配由26个英文字母的小写组成的字符串
^[A-Za-z0-9]+$ //匹配由数字和26个英文字母组成的字符串
^\w+$ //匹配由数字、26个英文字母或者下划线组成的字符串
if (!RegEx.IsMatch(textbox1.Text, "^[A-Za-z]+$"))