紧急求救,又是readfile()!问题解决,另加分!
在串口通信时,我用writefile()发送指令给我的仪器(万用电表),仪器能作出正确反应并显示结果。仪器说明书上说,已经将结果输出到输出缓冲区了。
我想用readfile()取出结果,ReadFile(hCom,&buff,300,&dReadNum,NULL)返回值为真,但dReadNum为0.
请不要建议用别的控件!
附代码:
//初始化端口
DCB ComDcb;
HANDLE hCom; //global handle
hCom = CreateFile("COM2",GENERIC_READ | GENERIC_WRITE,0,
NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
// LPBYTE buff = new BYTE[100];
// char* buff=new char[100];
BYTE buff[300];
memset(buff,0,300);
if(hCom==INVALID_HANDLE_VALUE)
{
ShowMessage("无法打开串行口");
return;
}
else
{
// ShowMessage("打开串行口suecess!");
COMMTIMEOUTS CommTimeOuts ;
SetCommMask(hCom, EV_RXCHAR ) ;
SetupComm(hCom,1024, 1024) ;
PurgeComm(hCom,PURGE_TXABORT|PURGE_RXABORT |
PURGE_TXCLEAR|PURGE_RXCLEAR);
CommTimeOuts.ReadIntervalTimeout = 0xFFFFFFFF ;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
CommTimeOuts.ReadTotalTimeoutConstant = 2000 ;
CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutConstant = 2000 ;
SetCommTimeouts(hCom, &CommTimeOuts );
ComDcb.DCBlength = sizeof(DCB) ;
GetCommState(hCom, &ComDcb) ;
ComDcb.BaudRate =9600;//波特率
ComDcb.ByteSize = 7;//数据位
ComDcb.Parity = 2; //校验 0-4=no,odd,even,mark,space
ComDcb.fRtsControl=RTS_CONTROL_HANDSHAKE;//流控制
ComDcb.fDtrControl=DTR_CONTROL_HANDSHAKE; //流控制
if(0==SetCommState(hCom,&ComDcb))
{
ShowMessage("aaaError!");
CloseHandle(hCom);
return;
}
}
DWORD dRead,dReadNum=0;
DWORD dwBytes;
//读写串口
WriteFile(hCom," *RST;",StrLen(" *RST;"),&dReadNum,NULL);
Sleep(50);
WriteFile(hCom," *CLS;",StrLen(" *CLS;"),&dReadNum,NULL);
WriteFile(hCom,"SYSTem:REMote;",StrLen("SYSTem:REMote;"),&dReadNum,NULL); //设置为远程控制
WriteFile(hCom,":MEAS:VOLT:DC?;",StrLen(":MEAS:VOLT:DC?;"),&dReadNum,NULL); //测量结果,此时已将结果置于输 出 缓冲区
Sleep(500);
bool a= ReadFile(hCom,&buff,300,&dReadNum,NULL);
buff[dReadNum+1]=0;
// Edit1->Text=String(buff);
WriteFile(hCom,":INITiate;",StrLen(":INITiate;"),&dReadNum,NULL);
//delete buff;
CloseHandle(hCom);
在VB中使用:
output(":MEAS:VOLT:DC?");
enter buff;已编译通过
[解决办法]
首先确定设置的波特率正确.代码中设断点,查看一下每个WriteFile以后dReadNum的值,确定写指令成功.
如果ReadFile仍然失败,查看一下GetLastError的值.