c#中接收16进制串口数据(com), 在textbox显示

static int buffersize = 18;   //十六进制数的大小(假设为9Byte,可调整数字大小)

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();
}

你可能感兴趣的:(接收,C#,串口,com,16进制,数据,接收数据,textBox,显示结果)