![](/img/trans.png)
[英]When is it good to use c++ iostreams over ReadFile, WriteFile, fprintf, etc …?
[英]C++ doesn't receive data with ReadFile/WriteFile when I'm trying to talk to a TTI device
我来找您是因为尝试编写支持TTI的QL355P的驱动程序时遇到了一些问题。 我已经用VB6编写了驱动程序,但是现在,我试图用C ++编写它。 我使用ReadFile / WriteFile函数与接口进行通信。 问题是当我发送识别命令(* IDN?)和endchar(。)时,我没有响应(我有Statut_timeout)。
我的代码是:
DCB l_dcb;
BOOL l_Success;
COMMTIMEOUTS l_TimeOuts;
const char *command = "*IDN?.";
// open an access to serial port
m_ComPort = CreateFile(L"COM2",
GENERIC_READ | GENERIC_WRITE,
0, // comm devices must be opened w/exclusive-access
NULL, // no security attrs
OPEN_EXISTING, // comm devices must use OPEN_EXISTING
0, // not overlapped I/O
NULL // hTemplate must be NULL for comm devices
);
// get the current configuration
l_Success = GetCommState(m_ComPort, &l_dcb);
// fill in the DCB with configuation:
// baud=19200, 8 data bits, no parity, 1 stop bit
l_dcb.BaudRate = 19200;
l_dcb.ByteSize = 8;
l_dcb.Parity = NOPARITY;
l_dcb.StopBits = ONESTOPBIT;
// configure the port
l_Success = SetCommState(m_ComPort, &l_dcb);
// get the current time-outs configuration
l_Success = GetCommTimeouts(m_ComPort, &l_TimeOuts);
// change the time-outs
l_TimeOuts.ReadIntervalTimeout=50;
l_TimeOuts.ReadTotalTimeoutMultiplier=50;
l_TimeOuts.ReadTotalTimeoutConstant=1000;
// sets the time-outs configuration
l_Success = SetCommTimeouts(m_ComPort, &l_TimeOuts);
// first purge the input buffer
PurgeComm(m_ComPort,PURGE_RXCLEAR);
// send the command
DWORD l_NumBytesTransfered=0;
DWORD l_NumBytesToTransfer=strlen(command);
l_Success = WriteFile(m_ComPort,command,l_NumBytesToTransfer,&l_NumBytesTransfered,NULL);
//Try to read
char l_Char='*';
int i=0;
char l_Pointer[100];
while(l_Char !=0x0a && i<100)
{
l_Success = ReadFile(m_ComPort,&l_Char,1,&l_NumBytesTransfered,NULL);
l_Pointer[i] = l_Char;
i++;
}
CloseHandle(m_ComPort); //close the handle
如果发生超时或各种可能的错误,ReadFile可以返回0。 您的代码段忽略了这种可能性,即使ReadFile失败,也会将垃圾放入输入数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.