读取串口 [英] reading serial port

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

问题描述

大家好,

我使用串行端口事件读取com数据.以下是我用来读取数据的编码.读取数据后,将其添加到portbuffer并调用 主要形式.

I’m using serial port event to read the com data. The below is the coding which I’m using to read the data. Once read the data, adding into portbuffer and invoking to main form.

现在我的问题是,有时读取方法给出了错误的值.发生此问题时,我需要重新启动应用程序以获取正确的数据.可能出问题的问题是什么 数据?

Now my problem is, sometime read method giving wrong value. When this problem occurred I need to restart the application to get correct data. What could be the problem to get wrong data?

 

private void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)

  {

   ReceiveData(); 

  }



  public void ReceiveData()

  {

   try

   {

    int intNumberOfBytesToRead = 0;

    intNumberOfBytesToRead = comPort.BytesToRead;



    byte[] arrayNewReceivedData = new byte[intNumberOfBytesToRead];

    comPort.Read(arrayNewReceivedData, 0, intNumberOfBytesToRead);

    portbuffer.AddRange(arrayNewReceivedData);



    m_MainWindow.Invoke(m_NotifyMainWindow, null, portbuffer,"","");

    portbuffer.Clear();

   }

   catch (Exception ex)

   {

    dtLogFile = DateTime.Now;

    objGlobalFunctions.WriteText(Application.StartupPath + "\\LogFiles", "ErrorLogs" + dtLogFile.ToString("yyyyMMdd") + ".txt","-:ReceiveData_ComPortEvents " + ex.Message, 1);

    m_MainWindow.Invoke(m_NotifyMainWindow, null, null, "", "ReceiveData_ComPortEvents --> " + ex.Message);

   }

  }

例如,我应该接收数据

#13,1,[@ 81 = 1403]
#13,1,[@ 82 = 2405]
#13,1,[@ 83 = 2010]

#13,1,[@81=1403]
#13,1,[@82=2405]
#13,1,[@83=2010]

 

但是有时我收到错误数据,如下所示

but sometime i'm receiving wrong data something like below

#13,1,[R18 $ 157797 ^ 1 = 50]

#13,1,[R18$157797^1=50]

 

推荐答案

您的代码中没有明显的错误.传输可能是罪魁祸首,否则设备会发疯.如果可行,我建议尝试使用超级终端或某些类似的应用程序模拟通信.

There is no obvious error in your code. A transmission is a possible culprit, or the device going berserk. If that's feasible, I would suggest trying simulating the communication using HyperTerminal or some similar application.

HTH
--mc

HTH
--mc


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

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