Serial communication - loopback

Hi, I have loopback on my serial port and I am trying to send byte via this port and receive it immediately. 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 doesn’t work. Port is opened successfully, setting were done, and It looks like byte was sent to port, but it can’t be received.
In my opinion problem should be in overlapped settings, probably I don’t 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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#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;
}
Topic archived. No new replies allowed.