Hi, I have loopback on my serial port and I am trying to send byte via this port and receive it immediately on the same computer. It has to be done overlapped (asynchronously) to send and receive in the same time, but I have no experiences with that. I wrote the code below, but it doesnt work. Port is opened successfully, settings were done, and It looks like byte was sent to port, but it cant be received.
In my opinion problem should be in overlapped settings, probably I dont properly understand how to set it. Otherwise I have no clue where to look for problem. Hardware is ok, I checked it.
Could anybody help? I appreciate all answers, thanks
In my opinion problem should be in overlapped settings, probably I dont properly understand how to set it. Otherwise I have no clue where to look for problem. Hardware is ok, I checked it.
Could anybody help? I appreciate all answers, thanks
Code:
#include <stdio.h>
#include <string.h>
#include <Windows.h>
int main (int argc, const char* argv[])
{
HANDLE COM;
OVERLAPPED m_OLRead,m_OLWrite;
DCB dcb = {0};
char buffer='i';
char prijem[10];
DWORD nWrite,nRead;
strcpy(prijem,"xxxxxxxxx");
COM=CreateFile(argv[1],GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0);
if (COM==INVALID_HANDLE_VALUE)
printf("CANNOT OPEN PORT %s\n\n",argv[1]);
else
printf("PORT %s WAS SUCCESSFULLY OPENED\n\n",argv[1]);
dcb.DCBlength = sizeof(DCB);
::GetCommState(COM,&dcb);
dcb.BaudRate = CBR_110;
dcb.ByteSize = 8;
dcb.Parity = ODDPARITY;
dcb.StopBits = TWOSTOPBITS;
::SetCommState (COM,&dcb);
SetCommMask(COM,EV_RXCHAR|EV_TXEMPTY); //sets notice while char received, or sent
m_OLRead.hEvent=::CreateEvent(NULL,TRUE,FALSE,NULL);
m_OLWrite.hEvent=::CreateEvent(NULL,TRUE,FALSE,NULL);
if (ReadFile(COM,&prijem,1,&nRead,&m_OLRead))
printf("error");
else
printf("reads\n");
if (WriteFile(COM,&buffer,1,&nWrite,&m_OLWrite))
printf("error");
else
printf("sends\n");
printf("sent %d bytes\n",nWrite);
WaitCommEvent(COM,&nWrite, &m_OLWrite);
if (nWrite==EV_TXEMPTY)
printf("all sent\n");
getchar();
CloseHandle(COM);
return 0;
}