static int buffersize = 18; //十六進制數的大小(假設為6Byte)
byte[] buffer = new Byte[buffersize]; //創建緩沖區
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Read(buffer, 0, buffersize);
string ss;
ss = byteToHexStr(buffer); //用到函數byteToHexStr
textBox2.Text = ss;
serialPort1.Close();
MessageBox.Show("數據接收成功!", "系統提示");
}
//字節數組轉16進制字符串
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;
}
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8; //數據位
serialPort1.Parity = System.IO.Ports.Parity.None; //無奇偶校驗位
serialPort1.StopBits = System.IO.Ports.StopBits.One; //一個停止位
serialPort1.ReadBufferSize = 1024; //接收緩沖區大小
serialPort1.Encoding = Encoding.BigEndianUnicode;
serialPort1.Open();
}
摘自 brian0031的專欄