c#通过DataReceived接收串口数据(转换16进制)

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.DtrEnable = Enabled; //很重要,部分设备可能会用到, 部分设备不会用到

    if (serialPort1.IsOpen)
    {
        serialPort1.Close();
    }
    textChanged += new UpdateTextEventHandler(ChangeText); //将事件处理方法添加到事件中去,不可缺少
    try
    {
        serialPort1.Open();
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(string.Format("未能打开串口,请检查是否连接。\n" + ex.Message));
        return;
    }

}

public static string ByteToHexStr(byte[] bytes) //函数,字节数组转16进制字符串
{
    string returnStr = "";
    if (bytes != null)
    {
        for (int i = 0; i < bytes.Length; i++)
        {
            returnStr += bytes[i].ToString("X2");
        }
    }
    return returnStr;
}

private delegate void UpdateTextEventHandler(string text);//定义委托

private event UpdateTextEventHandler textChanged;//定义事件

private void ChangeText(string text) //事件处理方法
{
    string text1 = string.Empty;
    text1 = text.Trim().Substring(10, 1);
    string s1 = string.Empty;
    s1 = text.Trim().Substring(10, 4);
    int dec1 = Convert.ToInt32(s1, 16); //s1 轉換成10進制
    if (text1 == "0") //直接除10
    {
        decimal dda1 = Math.Round((decimal)dec1 / 10, 1); //除10,保留1位小數
        textBox5.Text = dda1.ToString(CultureInfo.InvariantCulture).Trim();
    }
    else //xor ffff
    {
        int d1 = (dec1 ^ Convert.ToInt32("FFFF", 16)) + 1;
        decimal dd1 = Math.Round((decimal)d1 / 10, 1); //除10,保留1位小數
        textBox5.Text = dd1.ToString(CultureInfo.InvariantCulture).Trim();
    }

    string s2 = text.Trim().Substring(14, 4);
    int d2 = Convert.ToInt32(s2, 16); //s2 轉換成10進制
    Decimal dd2 = Math.Round((decimal)d2 / 10, 2); //除10,保留1位小數
    textBox6.Text = dd2.ToString(CultureInfo.InvariantCulture).Trim();

    string text3 = text.Trim().Substring(18, 1);
    string s3 = text.Trim().Substring(18, 4);
    int dec3 = Convert.ToInt32(s3, 16); //s3 轉換成10進制
    if (text3 == "0")
    {
        decimal dda3 = Math.Round((decimal)dec3 / 10, 1); //除10,保留1位小數
        textBox7.Text = dda3.ToString(CultureInfo.InvariantCulture).Trim();
    }
    else //xor ffff
    {
        int d3 = (dec3 ^ Convert.ToInt32("FFFF", 16)) + 1;
        decimal dd3 = Math.Round((decimal)d3 / 10, 1); //除10,保留1位小數
        textBox7.Text = string.Format("-{0}", dd3.ToString(CultureInfo.InvariantCulture).Trim());
    }
}

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    System.Threading.Thread.Sleep(100); //读取速度太慢,加Sleep延长读取时间, 不可缺少
    serialPort1.Read(buffer, 0, buffersize);
    //string text = Encoding.ASCII.GetString(buffer); //ASCII卡码
    string txt = ByteToHexStr(buffer); //用到函数,作用:转换16进制
    serialPort1.DiscardInBuffer();
    this.Invoke(textChanged, new string[] {txt}); //通过Invoke调用事件
}

没有更多推荐了,返回首页