2
我遇到了串口代码的问题。串行端口,WriteFile影响ReadFile
我只是做:
opencomm();
send();
closecomm();
和ClearCommError() (inside recv())
回报 comstat.cbInQue
已发送相同的金额。
所以,如果sizeof (sendbuff)
是100, 我在comstat.cbInQue
得到100。
读取一个字节与ReadFile
,comstat.cbInQue
递减后(当然在后续ClearCommError()
后)。
读取的值不是写入的值。 没有设备连接到端口。
最奇怪的是这个代码曾经工作,但不再。
WORD sendbuff[128];
static HANDLE hComm;
static void opencomm (void)
{
static COMMTIMEOUTS timeouts = {0,0,0,0,0};
static DCB dcb = {
sizeof (DCB), // DCBlength
115200, // * BaudRate
1, // fBinary
0, // * fParity
0, // fOutxCtsFlow
0, // fOutxDsrFlow
0, // fDtrControl
0, // fDsrSensitivity
1, // fTXContinueOnXoff
0, // fOutX
0, // fInX
0, // fErrorChar
0, // fNull
0, // fRtsControl
0, // fAbortOnError
0, // fDummy2
0, // wReserved
8*k, // XonLim
2*k, // XoffLim
8, // * ByteSize
0, // * Parity
0, // * StopBits
0, // XonChar
1, // XoffChar
0, // ErrorChar
0, // EofChar
0, // EvtChar
0 // wReserved1
};
hComm = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hComm != INVALID_HANDLE_VALUE) {
SetupComm(hComm, 16*k, 16*k);
SetCommState(hComm, &dcb);
SetCommTimeouts(hComm, &timeouts);
}
}
static void closecomm (void)
{
CloseHandle(hComm);
}
static BYTE recv (void)
{
BYTE text;
DWORD temp;
COMSTAT comstat;
while (1) {
ClearCommError(hComm, &temp, &comstat);
if (comstat.cbInQue != 0) break;
Sleep(1);
}
ReadFile(hComm, &text, 1, &temp, NULL);
return text;
}
static void send (void)
{
DWORD temp;
// send to other comp
WriteFile(hComm, sendbuff, sizeof (sendbuff), &temp, NULL);
// check other comp done
if (recv() != 0xAA) {
Beep(1000, 100);
quit(); // comm error
}
}
为了完整性,请包含'sendbuff'的** real **声明,它的外观在同一个源文件中位于这些函数之上。 – WhozCraig 2013-04-20 08:49:32
增加了sendbuff。人们可能会抱怨sendbuff未被初始化,这就是为什么我第一次没有包含它。 – aleksazr 2013-04-20 09:02:32