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

本文介绍了一个使用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

VB.NET中,通过SerialPort组件操作串口进行RAR文件的发送接收需要一些特定步骤。这里提供一个简化的示例,展示如何发送文件,但请注意这只是一个基本框架,实际应用可能需要更复杂的错误处理和文件读取/解压缩功能。 **发送RAR文件:** ```vb.net Imports System.IO.Compression Public Sub SendRARFile(ByVal comport As String, ByVal filePath As String) ' 创建SerialPort实例 Dim serialPort As New SerialPort(comport) ' 设置波特率、数据位数等配置 serialPort.BaudRate = 9600 ' 示例值,根据实际情况调整 serialPort.Parity = Parity.None serialPort.StopBits = StopBits.One ' 打开串口 serialPort.Open() ' RAR文件发送 Try ' 使用FileStream打开RAR文件并读取数据 Using fs As FileStream = File.OpenRead(filePath) Dim buffer(sizeOf(fs.ReadByte())) As Byte Dim readBytes As Integer While (readBytes = fs.Read(buffer, 0, buffer.Length)) ' 发送数据到串口 serialPort.Write(buffer, 0, readBytes) End While End Using Catch ex As Exception Console.WriteLine("Error sending file: " & ex.Message) Finally ' 关闭串口 serialPort.Close() End Try End Sub ``` **接收RAR文件:** ```vb.net Public Sub ReceiveRARFile(ByVal comport As String, ByVal savePath As String) Dim serialPort As New SerialPort(comport) ' ... (设置串口配置同上) ... serialPort.DataReceived += AddressOf OnDataReceived serialPort.Open() Private Sub OnDataReceived(sender As Object, e As SerialDataReceivedEventArgs) ' 读取接收到的数据到临时文件 Dim tempFileName As String = Path.Combine(savePath, "temp.rar") Using sw As New BinaryWriter(File.Create(tempFileName)) While serialPort.BytesToRead > 0 Dim bytesRead As Integer = serialPort.ReadExisting() sw.Write(bytesRead) End While End Using ' 文件传输完毕后,你可以尝试解压这个临时文件 Dim decompressResult As Boolean = DecompressTempFile(tempFileName) If decompressResult Then Console.WriteLine("Decompression successful.") Else Console.WriteLine("Decompression failed.") End If End Sub ' 自定义解压函数 Private Function DecompressTempFile(ByVal srcFilePath As String) As Boolean ' 这里可以使用RarLibrary库或者其他解压工具库来解压缩 ' 根据库的具体API来实现 End Function End Sub ``` 注意:在实际应用中,你需要确保已经安装了用于解压RAR文件的库,并且可能需要处理接收到的数据流,以及错误处理和分块传输等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值