使用 VB.net 语句检查串行端口接收"IF"数据



我可以从串行端口接收数据,但我想检查接收数据。

这是代码:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
   If int = 0 Then
     If SerialPort1.ReadExisting() = "a" Then
       'Do Something i want
     End If
   End If

因此,我使用了"ReadExisting()"函数来接收数据。它允许我接收数据,但不让我检查接收到的数据。

"我想检查收到的数据,如果收到的数据与作为"字符-a"然后必须做我想要的任务。"

高级感谢。:)

如果你真的必须通过轮询接收缓冲区来实现这一点,下面是我建议的代码来解决你的问题:

 Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
     If SerialPort1.BytesToRead > 0 Then
        'once anything have been received and stored in inner buffer.
         If SerialPort1.ReadChar() = "a" Then
               'Do Something you want
         End If
     End If
   End Sub

其概念是,检查接收缓冲区中是否存在任何内容,如果存在,则读取一个字符。如果out字符有效,请执行自己的操作。

顺便说一句,如果串行端口上没有接收到任何东西,使用ByteToRead进行预检查可以防止在调用ReadChar时阻止计时器。

最新更新