Hi All,
Currently I try to write a serial port communication in VC++ to transfer data from PC and robot via XBee transmitter. But after I wrote some commands to poll data from robot, I can not receive anything from the robot (the output of buffer is empty.). One problem may be that I have no idea how big of data I will receive from robot. So I am not sure whether I set the size of "buffer" to 257 is correct. In addition, the output of "error" is always 1. Because my MATLAB interface works, so the problem should happen in the code not the hardware or communication. Would you please give me help?
#include "StdAfx.h"
#include <iostream>
#define WIN32_LEAN_AND_MEAN //for GetCommState command
#include "Windows.h"
#include <WinBase.h>
using namespace std;
int main(){
char init[]="";
HANDLE serialHandle;
serialHandle = CreateFile("\\\\.\\COM8", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
DCB serialParams;
DWORD read, written;
serialParams.DCBlength = sizeof(serialParams);
if((GetCommState(serialHandle, &serialParams)==0))
{
printf("Get configuration port has a problem.");
return FALSE;
}
GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = CBR_57600;
serialParams.ByteSize = 8;
serialParams.StopBits = ONESTOPBIT;
serialParams.Parity = NOPARITY;
serialParams.fOutX=false;
serialParams.fInX=false;
serialParams.fOutxCtsFlow=true;
serialParams.fOutxDsrFlow=true;
serialParams.fDsrSensitivity=true;
serialParams.fRtsControl=RTS_CONTROL_HANDSHAKE;
serialParams.fDtrControl=DTR_CONTROL_HANDSHAKE;
if (!SetCommState(serialHandle, &serialParams))
{
printf("Set configuration port has a problem.");
return FALSE;
}
GetCommState(serialHandle, &serialParams);
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 3;
timeout.ReadTotalTimeoutConstant = 3;
timeout.ReadTotalTimeoutMultiplier = 3;
timeout.WriteTotalTimeoutConstant = 3;
timeout.WriteTotalTimeoutMultiplier = 3;
SetCommTimeouts(serialHandle, &timeout);
if (!SetCommTimeouts(serialHandle, &timeout))
{
printf("Set configuration port has a problem.");
return FALSE;
}
WriteFile(serialHandle,">*>p4",strlen(">*>p4"),&written,NULL);
char buffer[257];
int t;
bool error;
DWORD numberOfBytesRead=0;
DWORD err = GetLastError();
for (int jj=0;jj<10;jj++)
{
error=ReadFile(serialHandle,LPVOID(buffer),255,&numberOfBytesRead,NULL);
buffer[numberOfBytesRead]=0;
cout<<buffer<<endl;
cout<<error;
}
CloseHandle(serialHandle);
return 0;
}