throw ex;
}
}
return -1;
}
#endregion
#region 获取串口
/// <summary>
/// 获取所有已连接短信猫设备的串口
/// </summary>
/// <returns></returns>
public string[] serialsIsConnected()
{
List<string> lists = new List<string>();
string[] seriallist = getSerials();
foreach (string s in seriallist)
{
}
return lists.ToArray();
}
#endregion
#region 获取当前全部串口资源
/// <summary>
/// 获得当前电脑上的所有串口资源
/// </summary>
/// <returns></returns>
public string[] getSerials()
{
return SerialPort.GetPortNames();
}
#endregion
#region 字节型转换16
/// <summary>
/// 把字节型转换成十六进制字符串
/// </summary>
/// <param name="InBytes"></param>
/// <returns></returns>
public static string ByteToString(byte[] InBytes)
{
string StringOut = "";
foreach (byte InByte in InBytes)
{
StringOut = StringOut + String.Format("{0:X2} ", InByte);
}
return StringOut;
}
#endregion
#region 十六进制字符串转字节型
/// <summary>
/// 把十六进制字符串转换成字节型(方法1)
/// </summary>
/// <param name="InString"></param>
/// <returns></returns>
public static byte[] StringToByte(string InString)
{
string[] ByteStrings;
ByteStrings = InString.Split(" ".ToCharArray());
byte[] ByteOut;
ByteOut = new byte[ByteStrings.Length];
for (int i = 0; i <= ByteStrings.Length-1 ; i++)
{
//ByteOut[i] = System.Text.Encoding.ASCII.GetBytes(ByteStrings[i]);
ByteOut[i] = Byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber);
//ByteOut[i] =Convert.ToByte("0x" + ByteStrings[i]);
}
return ByteOut;
}
#endregion
#region 十六进制字符串转字节型
/// <summary>
/// 字符串转16进制字节数组(方法2)
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
#endregion
#region 字节型转十六进制字符串
/// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
#endregion
}
}
======================================================================================
调用方法:
static SerialClass sc = new SerialClass();
static void Main(string[] Args)
{
sc.DataReceived += new SerialClass.SerialPortDataReceiveEventArgs(sc_DataReceived);
sc.writeData("at");
Console.ReadLine();
sc.closePort();
}
static void sc_DataReceived(object sender, SerialDataReceivedEventArgs e, byte[] bits)
{
Console.WriteLine(Encoding.Default.GetString(bits));
}
推荐阅读
- C#帮助类,各种功能性代码,可以直接拿来即用
- 普洱茶贮藏方式,普洱茶有哪些类型
- 好看的黑暗系动漫 黑暗系动漫推荐
- 酸辣扇贝肉
- 说茶
- 二战是人类历史上规模最大战争 二战后最大规模战争
- 1969年人类第一次登上月球的宇航员 第一艘登上月球的飞行器是
- 手机突然字体变大,屏幕四周一个红框,无法操作 怎么办
- 手机耗电最快的三类软件,学生党:第二类戒不了,充电也要玩
- 阴阳师|阴阳师日亚服愚人节硬核整活操作平安京专属鱼塘玩家:我要这个