1、通过Message.show进行错误信息显示的方法:
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
2、其中使用C#进行串口通信的工程代码下载地址为:
3、通过C#如何发送、接受16进制的数据:
其中C#存放16进制数是使用变量byte,其在byte存放的数据会自动转换为10进制数,如果byte跟某个16进制数比较大小,则是如下:
byte date=0x10;
if(data==0x10)或者if(data==16)
如果跟某个硬件进行协议传输时,可以按着协议来编写代码。其如下:
其中某个协议如下:
//记住校验和要跟着价格改变
public static byte[] sendData = {
0xFA,0x50,0x12,0x0A,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x12,0x34,0x56,0x78,
0x64,0x00,0x00,0x00,
0x82,0xEB
};
设置价格代码为:
public static bool SetPrice(string price)
{
if (com == null)
{
com = Open();
if (com == null)
return false;
com.DataReceived += new SerialDataReceivedEventHandler(DealData);
}
Match match = Regex.Match(price, @"^(([1-9][0-9]*)|[0-9])(\.([0-9]{0,2}))?$");
if (!match.Success)
{
MessageBox.Show("价格错误");
return false;
}
float allprice = float.Parse(price);
int allprice1 = (int)(allprice * 10 * 10);
//int allprice1 = (int)(allprice * 100);
byte[] intbuff = BitConverter.GetBytes(allprice1);
Console.WriteLine("{0}", intbuff.Length);
sendData[17] = intbuff[0];
sendData[18] = intbuff[1];
sendData[19] = intbuff[2];
sendData[20] = intbuff[3];
byte checksum = 0;
for (int i = 3; i < 21; i++)
{
checksum += sendData[i];
}
sendData[21] = checksum;
try
{
com.DiscardInBuffer();
Console.Write("start!\n");
com.DiscardOutBuffer();
com.Write(sendData, 0, sendData.Length);
Console.Write("end\n");
}
catch (Exception e)
{
return false;
}
return true;
}
4、把字符串每两位组成一个16进制并通过串口进行发送(BCD码可能用到):
通讯里的发送的都是byte,我们其实需要转换的是在转成16进制后强制转换位byte即可转换成byte的发送数据。例子:
public static byte[] HexStringToByteArray(string s)
{
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}
string datapacket = "f02e00010200ff";
byte[] array=HexStringToByteArray(datapacket);
serialPort1.Write(array, 0, array.Length);
其中对应一些卡机当获得的卡号是一串字符串时并且其跟发送指令里的卡号是一致时。需要把这些数据通过串口发送给其它设备,如果我们发送的hex指令,由于其是由16进制,则相当于我们只需把字符串每两位变成十六进制即可。