学习VB.net串口发送与接收(二)

Imports System.IO.Ports
Imports System.Text

Public Class Form1
    Dim WithEvents Rs232 As SerialPort
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        For Each a As String In SerialPort.GetPortNames()
            CmbCom.Items.Add(a)
        Next
        CmbCom.SelectedIndex = 0
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim mPortName As String
        Dim mBuandBit As Integer
        Dim mDataBit As Integer
        Dim mStopBit As IO.Ports.StopBits
        Dim mParityBit As IO.Ports.Parity
        mPortName = CmbCom.SelectedItem.ToString
        mBuandBit = 9600
        mDataBit = 8
        mStopBit = StopBits.One
        mParityBit = Parity.None
        Rs232 = New SerialPort(mPortName, mBuandBit, mParityBit, mDataBit, mStopBit)
        If Not Rs232.IsOpen Then
            Rs232.Open()
            btnSend.Enabled = True
            Timer1.Interval = 100
            Timer1.Enabled = True
            MsgBox("~~通讯端口打开成功!~~", MsgBoxStyle.OkCancel)
        Else
            MsgBox("~~通讯端口打开失败(通讯端口已打开)~~", MsgBoxStyle.OkCancel)
        End If
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Dim Inbyte() As Byte, ReadCount As Integer
        If Rs232.BytesToRead <= 0 Then Exit Sub
        ReDim Inbyte(Rs232.BytesToRead - 1)
        ReadCount = Rs232.Read(Inbyte, 0, Rs232.BytesToRead)
        If ReadCount = 0 Then
            Exit Sub
        Else
            For Each bData As Byte In Inbyte
                txtReceive.Text += bData.ToString & vbCrLf
            Next
        End If
    End Sub

    Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
        If Rs232 Is Nothing OrElse Not Rs232.IsOpen Then
            MsgBox("~~通讯端口尚未打开~~", MsgBoxStyle.Critical Or MsgBoxStyle.OkCancel)
        Else
            btnSend.Enabled = False
            Timer1.Enabled = False
            Rs232.Close()
        End If
    End Sub

    Private Sub btnEnd_Click(sender As Object, e As EventArgs) Handles btnEnd.Click
        If Not Rs232 Is Nothing Then
            If Rs232.IsOpen Then Rs232.Close()
        End If
    End Sub

    Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
        Dim bDataOut(0) As Byte
        Try
            bDataOut(0) = CType(txtSend.Text, Byte) '文本中输入0-255的数字
            Rs232.Write(bDataOut, 0, 1)
        Catch ex As Exception
            MsgBox(ex.Message.ToString(), MsgBoxStyle.OkCancel)
        End Try
    End Sub
End Class

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值