I am attempting to write to the serial port of a robot I have. I can make the connection successfully, but when I attempt to write to the port it always fails. perhaps I am using the WriteABuffer functoin wrong. Any suggestions?
Here is my write a buffer code and the thread that calls it.
CODE
BOOL WriteABuffer(char * lpBuf, DWORD dwToWrite)
{
OVERLAPPED osWrite = {0};
DWORD dwWritten;
BOOL fRes;
// Create this writes OVERLAPPED structure hEvent.
osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osWrite.hEvent == NULL)
// Error creating overlapped event handle.
return FALSE;
// Issue write.
if (!WriteFile(outputPort, lpBuf, dwToWrite, &dwWritten, &osWrite)) {
if (GetLastError() != ERROR_IO_PENDING) {
// WriteFile failed, but it isn't delayed. Report error and abort.
fRes = FALSE;
}
else {
// Write is pending.
if (!GetOverlappedResult(outputPort, &osWrite, &dwWritten, TRUE))
fRes = FALSE;
else
// Write operation completed successfully.
fRes = TRUE;
}
}
else
// WriteFile completed immediately.
fRes = TRUE;
CloseHandle(osWrite.hEvent);
return fRes;
}
CODE
void WINAPI serialMonitor()
{
char buffer[255]="128 131";
DWORD test=7;
bool con=false;
printf("Serial Monitor initialized...\n");
HANDLE output = CreateFile(outputPort,GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0);
if (output == INVALID_HANDLE_VALUE){
con = false;
printf("\t Connection to robot failed...\n");
}
else{
con = true;
printf("\t Connection to robot succesful...\n");
}
//Create Input Monitor if Serial initializes Correctlly
if(con){
inputThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)inputMonitor, 0, 0, 0);
Sleep(100);
}
//Transmission Loop
if(WriteABuffer(buffer,test))
{
printf("Transmition complete...\n\n");
}
else
printf("Transmition failed...\n\n");
if(!con){
WaitForSingleObject(inputThread,INFINITE);
printf("Exiting...\n");
return;
}
else
printf("Input thread closed, serial communication must be complete...\n");
}
The functoin always returns false and to robot is obviously not receiving the correct input.
The command "128 131" should drop it into full mode.