I have a device that is connected on port COM4, (115200 baud, 8-N-1). Based on examples I found here I'm opening the port with:
Keyboard_Handle=CreateFile("\\\\.\\COM4",GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL); if(GetLastError() !=0 || Keyboard_Handle == INVALID_HANDLE_VALUE) { AfxMessageBox("Error opening connection to Keyboard"); exit(1); } char buffer[100]; strcpy(buffer,"baud=115200 parity=N data=8 stop=1"); BuildCommDCB((char*)&buffer,&dcb)) if(GetCommState(Keyboard_Handle, &dcb)) { dcb.BaudRate = CBR_115200; dcb.ByteSize = 8; dcb.Parity = 0; dcb.StopBits = 1; SetCommState(Keyboard_Handle, &dcb); }
Later in my code I call WriteFile on the port with:
LPDWORD bytes_written; LPDWORD bytes_read; LPOVERLAPPED OVERLAP; char write_buf[10]; write_buf[0] = 's'; write_buf[1] = '\0'; if(Keyboard_Handle != NULL) { WriteFile(Keyboard_Handle, (LPCVOID)write_buf , strlen(write_buf), bytes_written, OVERLAP); }
And every time I run the code I get the JIT Debugger complaining about an unhandled exception (though the WriteFile is inside a Try/catch block).
Is there something wrong with how I'm doing this?
Best Answer
bytes_written
needs to be an address of a variable; the compiler wouldn't compile the statement you posted.Likewise, "
OVERLAP
" doesn't make sense.Did you check whether
CreateFile
succeeded?What's in
write_buf
when you callstrlen
on it?Try copy-and-pasting the actual code that you're using.
Also that doesn't seem like a very good/informative sample that you're using. Try Windows Serial Port Programming and http://msdn.microsoft.com/en-us/library/ms810467.aspx
Also start with the sample program from the Microsoft site, test it before you modify it (to check that it's working on your machine) and then modify it.