主要作用:清除發送字串轉位元組中的空格和16進制前綴0x,
位元組轉換按兩位字符轉換為一個位元組,多余一位按一位字符轉換一個位元組
//清除空格和16進制前綴發送
String sendstr;// = new String [textBox1.Text.Length]
sendstr = textBox1.Text;
//這里采用substring較麻煩,不能使用split,因為sendstr為隱形string[],應該還可以用remove(未嘗試過)
//清除發送字串轉位元組中的空格和16進制前綴0x
sendstr = sendstr.Replace(" ", "");
sendstr = sendstr.Replace("0x", "");
byte[] Data = https://www.cnblogs.com/wdndmfirst/p/new byte[1];
try
{
if (serialPort1.IsOpen)
{
if (textBox1.Text != "")
{
//位元組轉換按兩位字符轉換為一個位元組,多余一位按一位字符轉換一個位元組
for (int i = 0; i < (sendstr.Length - sendstr.Length % 2) / 2; i++)
{
Data[0] = Convert.ToByte(sendstr.Substring(i * 2, 2), 16);
serialPort1.Write(Data, 0, 1);
}
if (sendstr.Length % 2 != 0)
{
Data[0] = Convert.ToByte(sendstr.Substring(sendstr.Length - 1, 1), 16);
serialPort1.Write(Data, 0, 1);
}
}
else
{
MessageBox.Show("發送區未輸入資料", "資料輸入提示");
}
//serialPort1.Write(recivebyte, 0, recivebyte.Length);
}
else
{
MessageBox.Show("串口未打開", "串口未打開提示");
}
}
catch
{
MessageBox.Show("發送出錯", "錯誤提示");
serialPort1.Close();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/333204.html
標籤:C#
