Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Serial port

Status
Not open for further replies.

JimmyK

Programmer
Sep 8, 2000
142
VN
Hi all,
I want to set baud rate of COM1 port, write something to COM1, and "listen" reply from devices connected to COM1.

How can i so that? please give a simple example

Jimmy

Thank you in advance

 
Hi Jimmy !

You can use the function CreateFile to open the port :
Code:
hComm=CreateFile(ComName,dwDesiredAccess,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
[\code]
This is an example to set up the port, but you should see the functions definitions :
[code]
	cc.dcb.BaudRate=CBR_115200;
	cc.dcb.ByteSize=8;
	cc.dcb.Parity=NOPARITY;
	cc.dcb.StopBits=ONESTOPBIT;

	if(!VerifySetup())
		return false;

	if(!SetDefaultCommConfig(nameport,&cc,sizeof(COMMCONFIG)))
		return false;
	SetCommState(hComm,&cc.dcb);
	return true;
[\code]

To listen to devices connected to the port, you should create a thread that reads character from the port.

This function reads one character from the port :
[code]
	DWORD NbBytesRead;
	COMSTAT comstat;
	DWORD errors;

	ClearCommError(hComm,&errors,&comstat);

	if (!comstat.cbInQue)
		return false;
	
	while (true)
	{
		if (!(ReadFile(hComm,buffer,1,&NbBytesRead,&o_read)))
		{
		//if the io operation is not terminated, it waits until it is

			NbBytesRead=0;
			if(GetLastError()==ERROR_IO_PENDING)
			{
				if(GetOverlappedResult(hComm,&o_read,&NbBytesRead,true))
				{					
					if (NbBytesRead)
						return true;
				}
			}
		
			else
			{
				MessageError(GetLastError());
				return false;
			}
		}
		else
			if (NbBytesRead)
				return true;
		ResetEvent(o_read.hEvent);
	}
	PurgeComm(hComm, PURGE_RXCLEAR);
	return false;
[\code]

I hope this can help you.
 
Thanks FoxJoker,
It really helps.

Jimmy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top