vb.net 编写的简易串口调试程序

Imports System
Imports System.IO.Ports

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles MyBase.Load
        '获取计算机有效串口
        Dim ports As String() = SerialPort.GetPortNames() '必须用命名空间,用SerialPort,获取计算机的有效串口
        Dim port As String
        For Each port In ports
            portnameBox.Items.Add(port) '向comboBox添加
        Next port
        '初始化界面
        baudrateBox.Text = baudrateBox.Items(2) '注释和不注释的地方可以替换
        portnameBox.Text = portnameBox.Items(0)
        'baudrateBox.Selectedindex() = 2
        ' portnameBox.Selectedindex() = 0
        Serial_Port1() '初始化串口
        Label3.Text = SerialPort1.IsOpen
        statuslabel.Text = "串口未连接"
        statuslabel.ForeColor = Color.Red
        sendBox.Text = "123"
        receivebytes.Text = "0"
        linecheck.Enabled = True
        timeBox.Enabled = True

    End Sub

    Private Sub Serial_Port1() '设置串口参数
        'SerialPort1.Baudrate = Val(baudrateBox.Text) '波特率
        'SerialPort1.PortName = portnameBox.Text '串口名称
        SerialPort1.PortName = portnameBox.SelectedItem
        SerialPort1.Baudrate = Val(baudrateBox.SelectedItem)
        SerialPort1.DataBits = 8 '数据位
        SerialPort1.StopBits = IO.Ports.StopBits.One '停止位
        SerialPort1.Parity = IO.Ports.Parity.None '校验位
    End Sub

    '关闭串口连接
    Private Sub closebtn_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles closebtn.Click
        Try
            SerialPort1.Close() '关闭串口
            Label3.Text = SerialPort1.IsOpen
            If SerialPort1.IsOpen = False Then
                statuslabel.Text = "串口未连接"
                statuslabel.ForeColor = Color.Red
                receiveBox.Text = ""
                receivebytes.Text = ""
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    '打开串口连接
    Private Sub openbtn_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles openbtn.Click
        Try
            SerialPort1.open() '打开串口
            Label3.Text = SerialPort1.IsOpen
            If SerialPort1.IsOpen = True Then
                statuslabel.Text = "串口已连接"
                statuslabel.ForeColor = Color.Green
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    '手动发送数据
    Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles Button1.Click
        send()
    End Sub

    '触发接收事件,接收数据
    Public Sub Sp_DataReceived(ByVal sender As Object,ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        Me.Invoke(New EventHandler(AddressOf Sp_Receiving)) '调用接收数据函数
    End Sub

    '接收数据过程
    Private Sub Sp_Receiving(ByVal sender As Object,ByVal e As EventArgs)

        ' Dim strIncoming As Byte
        Dim strIncoming As Integer
        Dim str1() As String
        Dim str2() As String
        Dim bytes() As Byte
        Dim i As Integer
        Try
            Threading.Thread.Sleep(100) '添加的延时
            receivebytes.Text = Str(Val(receivebytes.Text) + SerialPort1.BytesToRead)
            If SerialPort1.BytesToRead > 0 Then

                ReDim bytes(SerialPort1.BytesToRead)
                'strIncoming = Convert.ToByte(SerialPort1.ReadByte())
                If receivecheck.Checked = True Then
                    strIncoming = SerialPort1.ReadByte()
                    bytes(0) = strIncoming
                    For i = 1 To SerialPort1.BytesToRead
                        strIncoming = SerialPort1.ReadByte() '读取缓冲区中的数据
                        bytes(i) = strIncoming
                    Next
                    ' SerialPort1.Write(sendBox.Text)'发送数据
                    SerialPort1.discardInBuffer()
                    str1 = Split(BitConverter.ToString(bytes),"-")

                    ReDim str2(str1.Length - 1) '去除str1中最后的字符
                    For i = 0 To str1.Length - 2
                        str2(i) = str1(i)
                    Next
                    receiveBox.Text = receiveBox.Text & Join(str2," ")
                    'BitConverter.ToString(bytes)
                Else
                    receiveBox.Text = receiveBox.Text & SerialPort1.ReadExisting()
                End If

            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    '更改串口设置
    Private Sub portnameBox_SelectedindexChanged(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles portnameBox.SelectedindexChanged
        Try
            Serial_Port1()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    '清空接收区
    Private Sub clearbtn_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles clearbtn.Click
        receiveBox.Text = ""
    End Sub

    '定时发送数据
    Private Sub Timer1_Tick(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles Timer1.Tick
        Timer1.Interval = timeBox.Text
        send()
    End Sub

    '选择定时发送的触发事件
    Private Sub timecheck_CheckedChanged(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles timecheck.CheckedChanged

        If timecheck.Checked = True Then
            If timeBox.Text = "" Then
                MsgBox("时间间隔不能为0")
                timecheck.Checked = False
            Else
                send()
                timeBox.Enabled = False
            End If
        Else
            timeBox.Enabled = True
        End If
    End Sub

    Public Sub send() '发送数据过程
        Dim databyte() As Byte
        Dim str1() As String
        Dim str2 As String
        Dim str3 As String
        Dim i As Integer

        Try
            If sendcheck.Checked = False Then '不按照16进制发送
                'timecheck.Enabled = True

                If linecheck.Checked = False Then '判断是否选中分行发送
                    SerialPort1.Write(sendBox.Text)
                Else
                    SerialPort1.WriteLine(sendBox.Text)
                End If

            Else '按照16进制发送
                If InStr(sendBox.Text," ") Then '判断是否有空格
                    str1 = Split(sendBox.Text)
                    str2 = Join(str1,"")
                Else
                    str2 = sendBox.Text
                End If

                If str2.Length Mod 2 = 0 Then '判断字符串字节数是否为偶数
                    ReDim databyte(str2.Length / 2) '重新定义数组
                    For i = 0 To str2.Length / 2 - 1
                        databyte(i) = Convert.ToByte(Mid(str2,2 * i + 1,2),16) '两个字符转换为一个16进制字节
                        'databyte(i) = Val(Mid(str2,2 * i + 1,2))
                    Next
                    SerialPort1.Write(databyte,0,databyte.Length - 1)
                    sendbytes.Text = Str(Val(sendbytes.Text) + databyte.Length - 1)
                Else

                    str3 = Mid(str2,1,(str2.Length - 1)) & "0" & Mid(str2,str2.Length)
                    ReDim databyte(str3.Length / 2)
                    For i = 0 To str3.Length / 2 - 1
                        databyte(i) = Convert.ToByte(Mid(str3,16)
                    Next
                    SerialPort1.Write(databyte,databyte.Length - 1)
                    sendbytes.Text = Str(Val(sendbytes.Text) + databyte.Length - 1)
                End If
                'databyte = System.Text.Encoding.Default.GetBytes(sendBox.Text)把每个字符转换成字节

            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub

    '是否按照16进制发送,如果是换行将不可选。如果不是,换行可选
    Private Sub sendcheck_CheckedChanged(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles sendcheck.CheckedChanged
        If sendcheck.Checked = True Then '不按照16进制发送
            linecheck.Enabled = False
        Else
            linecheck.Enabled = True
        End If
    End Sub
End Class

程序包括16进制发送和接受,定时发送,换行接收,接收和发送数据字节统计

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...