简体   繁体   English

在VB.net中使用“ IF”语句检查串行端口接收到哪些数据

[英]Check which data is received by serial port with “IF” statement in VB.net

I am able to receive data from serial port, but i want to check which data is received. 我能够从串行端口接收数据,但是我想检查接收到的数据。

Here is the code : 这是代码:

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

So, i used "ReadExisting()" funtion for receiving data. 因此,我使用“ ReadExisting()”功能接收数据。 It allows me receive data but, not let me check what data is received. 它允许我接收数据,但不能让我检查接收到了什么数据。

"I want to check the received data and if data is received is same as as 'Character - a' then have to do the task i want." “我想检查接收到的数据,如果接收到的数据与'字符-a'相同,则必须执行我想要的任务。”

Thanks in Advanced. 提前致谢。 :) :)

If you do really have to achieve it by polling receiving buffer , here's my suggested code to solve your question: 如果您确实必须通过轮询接收缓冲区来实现它,这是我建议的代码来解决您的问题:

 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

The concept is , check if there's anything existed in receiving buffer , if it was , read one char out. 概念是,检查接收缓冲区中是否存在任何内容,如果存在,则读出一个字符。 If the out char is valid , do your own actions. 如果out char有效,请执行您自己的操作。

By the way , using ByteToRead to do pre-check could prevent your timer be blocked when calling ReadChar , if nothing be received on serial port. 顺便说一句 ,如果在串行端口上什么都没收到,那么使用ByteToRead进行预检查可以防止在调用ReadChar时阻塞计时器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM