串口接收数据时,会关闭串口,不知道什么原因,代码如下

liyunpeng_111 2007-12-10 10:45:51
public: void SynReceiveData()
{
//想获取缓存区的数据到来信号。问题1:串口的触发事件有哪些?如何定义?
SerialDataReceivedEventArgs^ type;


do
{
System::Threading::Thread::Sleep(0);

//堵塞到数据到来或超时
if(SerialData::Chars)//接受缓存是否有信号到来。
{
try
{
Byte firstByte=Convert::ToByte(serialPort1->ReadByte());//问题就在这里。当执行到这条语句,就会出现异常,串口关闭,请问是为什么??
int bytesRead=serialPort1->BytesToRead;
bytesData=new Byte[bytesRead];
bytesData[0]=firstByte;

for(int i=0;i<=bytesRead;i++)

bytesData[i]=Convert::ToByte(serialPort1->ReadByte());

listdata=Convert::ToString(bytesData);
listBox->Text=listdata;


}
catch(System::Exception^ e)
{
MessageBox::Show(Convert::ToString(e));
}
}

}while(1);



}

void ReceiveData(SerialPort^ serialport)
{
Form1^ start=gcnew Form1;
Thread^ threadreceive=gcnew Thread(gcnew ThreadStart(start,&Form1::SynReceiveData));
threadreceive->Start();
}
...全文
238 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
瓶盒 2007-12-11
  • 打赏
  • 举报
回复
serialPort1是什么类?只知道在C++中是无法真接访问串口IO的,必须通过加载第三方的写IO的驱动才有权利
liyunpeng_111 2007-12-11
  • 打赏
  • 举报
回复
void receivedEvent(Object^ serialportobj,SerialDataReceivedEventArgs^ type)
{


try
{
Byte firstByte=Convert::ToByte(serialPort1->ReadByte());
int bytesRead=serialPort1->BytesToRead;
bytesData=new Byte[bytesRead];
bytesData[0]=firstByte;

for(int i=0;i<=bytesRead;i++)

bytesData[i]=Convert::ToByte(serialPort1->ReadByte());

listdata=Convert::ToString(bytesData);
listBox->Text=listdata;


}
catch(System::Exception^ e)
{
MessageBox::Show(Convert::ToString(e));
}


}

public: void SynReceiveData()
{


serialPort1->DataReceived+=receivedEvent;//这条语句能详细解释一下吗?越详细越好。。。出现的错误: “comm::Form1::receivedEvent”: 函数调用缺少参数列表;请使用“&comm::Form1::receivedEvent”创建指向成员的指针;事件应该怎么定义啊?

}

void threadReceive()
{
Form1^ start=gcnew Form1;
Thread^ threadreceive=gcnew Thread(gcnew ThreadStart(start,&Form1::SynReceiveData));
threadreceive->Start();
}
liyunpeng_111 2007-12-11
  • 打赏
  • 举报
回复
谢谢3楼。
事件不会用,能不能给段事件引用人代码,参考一下
liyunpeng_111 2007-12-11
  • 打赏
  • 举报
回复
异常:
system.invalidoperationexception:端口被关闭。
在system.io.ports,serialport.readbyte()
comm.form1.synreceivedata()
真相重于对错 2007-12-11
  • 打赏
  • 举报
回复
想获取缓存区的数据到来信号。问题1:串口的触发事件有哪些?如何定义?
=======================================================
名称 说明
DataReceived 表示将处理 SerialPort 对象的数据接收事件的方法。
Disposed 添加事件处理程序以侦听组件上的 Disposed 事件。 (从 Component 继承。)
ErrorReceived 表示处理 SerialPort 对象的错误事件的方法。
PinChanged 表示将处理 SerialPort 对象的串行管脚更改事件的方法。
真相重于对错 2007-12-11
  • 打赏
  • 举报
回复
什么异常??

7,540

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 VC.NET
社区管理员
  • VC.NET社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧