使用PORT读取机器的重量 [英] Reading Weight from Machine Using PORT

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

问题描述

大家好,



我正在使用此代码读取称重机的重量。



 _ serialPort =  new  SerialPort(  COM2 9600 ,Parity.None, 8 ); 
if (!_serialPort.IsOpen)
{
_serialPort.Open();
}
_serialPort.DataReceived + = new SerialDataReceivedEventHandler(_serialPort_DataReceived);

txtQty.Text = _serialPort.ReadExisting();
if (_serialPort.IsOpen)
{
_serialPort.Close();
}









此代码工作正常检查断点。但不是在exe中工作。有时得到这个访问端口'COM2'被拒绝



如何解决这个问题?

解决方案

< blockquote>它有可能在调试器中运行,因为你的断点允许有足够的时间让串口实际接收一些信息。



串口是物理通信设备 - 数据传输不会立即发生。在您的情况下,传输速率为每秒9600位,每秒大约960个字符。你不能只是打开端口,设置处理程序,读取数据和关闭处理程序,因为在现实世界中可能有或没有数据可用,如果一个字符在错误的时间到达接收器,接收事件处理程序将触发后可能会在代码示例关闭端口后执行。这可能会导致您描述的问题。



使用处理程序事件来读取数据。

如果您要添加一个处理程序每​​次打开端口时,每次关闭它时都需要删除处理程序!


Hi All,

I am using this code to read weight from weighing machine.

_serialPort = new SerialPort("COM2", 9600, Parity.None, 8);
   if (!_serialPort.IsOpen)
  {
     _serialPort.Open();
  }
  _serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);

  txtQty.Text  = _serialPort.ReadExisting();
  if (_serialPort.IsOpen)
     {
        _serialPort.Close();
     }





This code working fine when I check with Break point. but not working in exe. Sometime getting this " Access to the port 'COM2' is denied"

How to resolve this ?

解决方案

The chance are that it is working in the debugger, because your breakpoint allows enough time for the serial port to actually receive some information.

Serial ports are physical communications devices - data transfer does not happen instantly. In your case, the transfer happens at a rate of 9600 bits per second, which works out at around 960 characters per second. You cannot just open the port, set a handler, read data and close the handler, because in the real world there may or may not be data available, and if a character arrives at the receiver at the wrong time, the receive event handler will be triggered and may get executed after the port is closed by your code sample. This could cause the problem you are describing.

Use the handler event to read the data.
And if you are going to add a handler every time you open the port, you need to remove the handler every time you close it!


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

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