自助推荐
立即入驻

VB.NET解析串口返回数据GB2312转UTF8

博客2年前更新 桔子雨
1,245 00

因为485返回的数据是ASCII的GB2312的编码,所以需要解析成UTF-8格式的方便储存。温湿度解码主要是解决表示温度的℃符号。

VB.NET解析串口返回数据GB2312转UTF8
Imports System.IO.Ports

Public Class Form1

    Private Sub comm_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles comm.DataReceived
        Dim buf(comm.ReadBufferSize) As Byte
        comm.Read(buf, 0, buf.Length)
        If Array.IndexOf(buf, CByte(13)) <> -1 Then
            Array.Resize(buf, Array.IndexOf(buf, CByte(13)))   '定位结束回车符号\n
        Else
            Debug.Print("返回数据的格式错误,没有发现回车结束符!")
            Exit Sub
        End If
        Dim s = System.Text.Encoding.GetEncoding("gb2312").GetString(buf)   'gb2312代码页面编号936
        Dim tmp() As String
        tmp = Split(s, ",")
        Debug.Print("当前温度:" & tmp(0) & " 当前湿度:" & tmp(1).Trim & " 当前时间:" & Now)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        '打开串口接受数据
        If Button2.Text = "开始调试串口" Then
            comm.PortName = "COM2"
            comm.Open()
            Button2.Text = "暂停调试串口"
        Else
            comm.Close()
            Button2.Text = "开始调试串口"
        End If
    End Sub
End Class

© 版权声明

相关文章