'直前の読み残しを保持しておく変数 Private cache As Byte() = {} Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived If Not SerialPort1.IsOpen Then Return End If Dim size As Integer = SerialPort1.BytesToRead If size + cache.Length >= 4 Then Dim bin(3) As Byte Array.Copy(cache, bin, Math.Min(4, cache.Length)) SerialPort1.Read(bin, Math.Min(4, cache.Length), Math.Max(0, 4 - cache.Length)) cache = New Byte() {} Dim pattern As Integer = 0 For n = 0 To 3 pattern *= 10 If bin(n) = &HFF Then pattern += 1 End If Next Dim value As UShort = UShort.MaxValue Select Case pattern Case 1100, 1110 'Ⓐパターン value = BitConverter.ToUInt16(bin, 2) cache = New Byte() {} Case 1001, 1101 'Ⓑパターン value = BitConverter.ToUInt16(bin, 1) cache = New Byte() {bin(3)} Case 11, 1011 'Ⓒパターン value = BitConverter.ToUInt16(bin, 0) cache = New Byte() {bin(2), bin(3)} Case 110, 111 'Ⓓパターン cache = New Byte() {bin(1), bin(2), bin(3)} Case Else 'Ⓔパターン '想定しないデータなので仕切り直し cache = New Byte() {} End Select If value <> UShort.MaxValue Then Invoke(Sub() ListBox1.Items.Insert(0, value)) End If End If