我正在使用win32 api,visual studio 2008。我能够从串行端口读取字节,但不是我想要的方式,我正在以x,y格式从arduino传递数据。但我下面的代码有时会先读取 y,然后读取 x。我怎样才能以正确的顺序读取数据,我的意思是按 x,y 顺序。如果有人感兴趣,坐标将被传递给另一个函数,鼠标光标将相应移动。这是我的代码:
int _tmain( int argc, TCHAR *argv[] )
{
HANDLE hComm;
DWORD bytesRead = 0;
POINT mouseCoords; /*structur to hold mouse coordinates*/
DCB dcb = {0}; /*Device Control Block, used to configure serial port settings
here we initialize dcb structure to zero. Good practice!*/
COMMTIMEOUTS ct;
int loop = 1;
int counter = 10;
/*get handle to serial port*/
hComm = CreateFile(g_pcCommPort,
GENERIC_WRITE | GENERIC_READ,
0, /* must be opened with exclusive-access */
NULL, /* default security attributes*/
OPEN_EXISTING, /* must use OPEN_EXISTING for serial ports*/
0, /*non overlapped I/O, blocking*/
NULL ); /*hTemplate must be NULL for comm devices*/
/*Make sure that serial port is successfuly opened*/
if ( hComm == INVALID_HANDLE_VALUE ) {
errMsg(TEXT("Cannot access serial port!"));
return 0;
}
ASSERT("Serial port access successful!");
/*get serial port status i.e default settings and make
sure we can access them*/
if ( !(GetCommState(hComm, &dcb))) {
errMsg(TEXT("Cannot access current DCB settings!"));
return 0;
}
ASSERT("DCB settings access successful!");
/*print dcb settings so that we can get an idea of default settings*/
printCommSettings(dcb);
/*Since we were successful in accessing the com port
we can go ahead and set it manually to our desired
settings*/
if ( !(setupSerialPort(&dcb))) {
errMsg(TEXT("Cannot setup serial port!"));
return 0;
}
ASSERT("DCB config successful!");
/*lets print configuration after setting up the
serial port just to make sure everything is ok*/
printCommSettings(dcb);
ct.ReadIntervalTimeout = 50;
ct.ReadTotalTimeoutConstant = 50;
ct.ReadTotalTimeoutMultiplier = 10;
ct.WriteTotalTimeoutConstant = 50;
ct.WriteTotalTimeoutMultiplier = 10;
if(SetCommTimeouts(hComm, &ct) == 0) {
errMsg(TEXT("Cannot setup comm timout!"));
}
while (loop)
{
if ( !(ReadFile(hComm,g_buffer,5,&bytesRead,NULL)) ) { loop = 0; }
printf("Message Read: %s==%d\r", g_buffer, bytesRead);
} /*while loop*/
if ( !(CloseHandle(hComm))) {
errMsg(TEXT("Serial port handle error!"));
}
NEWLINE;
return 0;
}
编辑:这些是串行端口设置:“9600,N,8,1”
我正在传递 10,12,这就是我得到的: 输出:
消息读取:,12
消息读取:10,12
消息读取:12
消息读取:0,12
消息读取:2
消息读取:,12
消息读取: 10,12
消息读取:12
消息读取:0,12
消息读取:2
消息读取:,12
消息读取:10,12