从串口读取问题 [英] Problems reading from serial port

查看:110
本文介绍了从串口读取问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

 我有一台摩托罗拉MC9090手持设备,它通过Com1连接到RFID阅读器。我试图显示rfid阅读器发送的任何内容,但到目前为止,这一切都没有。可能是rfid阅读器需要一个我无法获得的API,但是我想b $ b喜欢这个。下面的代码是我尝试过的众多代码之一,但它没有返回任何内容。如果rfid阅读器有任何要发送的内容,你能否确认:

  I have a Motorola MC9090 handheld device which is connect via Com1 to an RFID reader. I am trying to display whatever the rfid reader sends but so far that is nothing. It could be that the rfid reader require an API which I cannot get but I would like to be sure of this. The code below is one of many I have tried but it doesn't return anything. Could you confirm that it should if the rfid reader had anything to send:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Try
      Dim port1 As New System.IO.Ports.SerialPort("COM1", 9600)
      port1.DataBits = 8
      port1.Parity = IO.Ports.Parity.None
      port1.StopBits = IO.Ports.StopBits.One

      port1.Open()

      Dim line As String
      While port1.BytesToRead > 0 
        line = port1.ReadLine
      End While

      port1.Close()
      TextBox1.Text = line
    Catch
      MsgBox("Failed")
    End Try


谢谢。

推荐答案

您正在设置应用程序甚至在它接收数据之前循环,当你打开端口时,RFID阅读器将不会发送任何东西,直到它得到发送的东西,所以你将立即有BytesToRead = 0并且循环关闭然后端口关闭。

You are setting your application in a loop even before it receives data, when you open the port, the RFID reader will not send anything until it gets something to send so you will immediately have BytesToRead = 0 and the loop closes then the port closes.

而不是使用这种方法,有一个名为

Instead of using this approach, there is an event called

DataReceived

DataReceived

当您从RFID阅读器获取新数据时,这甚至会触发,您可以进行所有处理。

this even will fire when you get new data from the RFID reader, inside that you can do all the processing.

记住,打开端口并订阅事件(我是一个C#家伙,所以我很抱歉没有在VB中提供它)

remember, open the port and subscribe to the event (i'm a C# guy so i'm sorry for not providing it in VB)

并且记得只在你完成后关闭端口,并且如果打开时总是关闭端口关闭应用程序,否则你可能需要软复位:S

and remember to close the port only when you are done, and ALWAYS close the port if open when closing the application otherwise you might have to softreset :S

 

这里是C#代码,希望你能转换它

here is the C# code, hope you can convert it

System.IO.Ports.SerialPort x = new System.IO.Ports.SerialPort();
private void Form1_Load(object sender, EventArgs e)
{
   x.Open();
   x.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(x_DataReceived);
      
}

void x_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
   // Do Read Data Here
}

不要忘记在某处关闭端口。

Don't forget to close the port somewhere.

我错过了上面的一点,当端口不是打开所有收到的数据都会被删除而不会排队,所以当端口关闭时你会错过数据。

One point that i have missed above, when the port is not open all received data is dropped and NOT queued so you will miss the data when the port is closed.

希望这有帮助。

 


这篇关于从串口读取问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆