从serialport读取512个字节,然后保存到.bin

时间:2018-02-26 02:54:51

标签: vb.net serial-port

我试图从串口读取512个字节,然后将其写入.bin文件。

Dim bufferLength As Int16 = 512
Private Sub readserial()

    Dim buffer(bufferLength - 1) As Byte

    SerialPort1.Read(buffer, 0, bufferLength)
    Using vFs As New FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\myfile.bin", FileMode.Append) 'save

        vFs.Write(buffer, 0, bufferLength)
    End Using

End Sub

吉姆的代码

  Dim bufferLength As Integer = 512
Dim buffer(bufferLength - 1) As Byte
Private Sub serialport1_datareceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
    If (SerialPort1.IsOpen) Then

        Do While SerialPort1.BytesToRead > 0

            Try



                SerialPort1.Read(buffer, 0, bufferLength)
            Catch
            End Try

        Loop
        Using vFs As New FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\myfile.bin", FileMode.Append) 'save

            vFs.Write(buffer, 0, bufferLength)
        End Using
    End If
End Sub

问题是.bin向我显示错误的数据。它将最后一个字节显示为文件中的第一个字节,然后全部为零,直到文件末尾。也许我错误地读数据或者我不知道,有什么帮助吗?

由于

0 个答案:

没有答案