serial port communication

answerme's Avatar, Join Date: Dec 2007
Ambitious contributor
Hye all
Below I have pasted my C serial port code .
Iam getting error
Code:
Cannot open Communication Port. error no.2
.
error no.2 specifies that system cannot find the file specified.
Does anyone have suggestion


Code:
#include "stdafx.h"
#include<windows.h>
#include<winbase.h>
#include <conio.h>

HANDLE hComm;
BOOL m_bPortReady;
DCB  m_dcb;
COMMTIMEOUTS m_CommTimeouts;
DWORD iBytesWritten;
int gle;

BOOL ConfigurePort(DWORD BaudRate, BYTE ByteSize, DWORD fParity, BYTE Parity, BYTE StopBits)
{
	if((m_bPortReady = GetCommState(hComm, &m_dcb))==0)
		{
			printf("GetCommState Error");getch();
			CloseHandle(hComm);
			return false;
		}
	m_dcb.BaudRate =BaudRate;
	m_dcb.ByteSize = ByteSize;
	m_dcb.Parity =Parity ;
	m_dcb.StopBits =StopBits;
	m_dcb.fBinary=TRUE;
	//m_dcb.fDsrSensitivity=false;
	m_dcb.fParity=fParity;
//	m_dcb.fOutX=false;
//	m_dcb.fInX=false;
//	m_dcb.fNull=false;
//	m_dcb.fAbortOnError=FALSE;
//	m_dcb.fOutxCtsFlow=FALSE;
//	m_dcb.fOutxDsrFlow=false;
	//m_dcb.fDtrControl=DTR_CONTROL_DISABLE;
	//m_dcb.fDsrSensitivity=false;
	//m_dcb.fRtsControl=RTS_CONTROL_DISABLE;
	//m_dcb.fOutxCtsFlow=false;
	//m_dcb.fOutxCtsFlow=false;

	m_bPortReady = SetCommState(hComm, &m_dcb);
	if(m_bPortReady ==0)
	{
		printf("SetCommState Error");getch();
		CloseHandle(hComm);
		return false;
	}
		return true;
}
BOOL SetCommunicationTimeouts(DWORD ReadIntervalTimeout, DWORD ReadTotalTimeoutMultiplier, DWORD ReadTotalTimeoutConstant, DWORD WriteTotalTimeoutMultiplier, DWORD WriteTotalTimeoutConstant)
{
if((m_bPortReady = GetCommTimeouts (hComm, &m_CommTimeouts))==0)
   return false;
m_CommTimeouts.ReadIntervalTimeout =ReadIntervalTimeout;
m_CommTimeouts.ReadTotalTimeoutConstant =ReadTotalTimeoutConstant;
m_CommTimeouts.ReadTotalTimeoutMultiplier =ReadTotalTimeoutMultiplier;
m_CommTimeouts.WriteTotalTimeoutConstant = WriteTotalTimeoutConstant;
m_CommTimeouts.WriteTotalTimeoutMultiplier =WriteTotalTimeoutMultiplier;
		m_bPortReady = SetCommTimeouts (hComm, &m_CommTimeouts);
		if(m_bPortReady ==0){
printf("StCommTimeouts function failed");getch();
		CloseHandle(hComm);
		return false;}
		return true;
}	

BOOL WriteByte(char* bybyte)
{
	iBytesWritten=0;
	if(WriteFile(hComm,bybyte,1,&iBytesWritten,NULL)==0)
		return false;
	else 
		return true;
}
BOOL ReadByte(char *resp)
{

	char rx;
	resp = 0;
	DWORD dwBytesTransferred=0;
	if(ReadFile (hComm, &rx, 1, &dwBytesTransferred, 0))
	{
		if (dwBytesTransferred == 1)
		{
			resp=&rx;
			return true;
		}
	return false;
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	
	hComm = CreateFile((LPCWSTR)"COM1",
                      GENERIC_READ | GENERIC_WRITE,
                      0,
                      0,
                      OPEN_EXISTING,
                      FILE_FLAG_OVERLAPPED,
					  0);

	if(hComm==INVALID_HANDLE_VALUE)
		{
			printf("Cannot open Communication Port..");
			gle = GetLastError();
			printf("error no.%d\n", gle);
			getch();
			return false;
		}

	DWORD data=0; 
	unsigned char a[2], b[1],buffer[10],sendb[14], *vptr;
	char *ptr; 
	char err[4];
	int slen;
	char rx = 0;
	char x[1];
	char bw;
	/*short int crcv;//unsigned char* ptr;
	unsigned char buff[10] = {0x1b,0x81,0x00,0x80,0x00,0x80,0x40,0x00,0x00,0x1};
	unsigned char buff[10] = {0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};
	crcv = Calc_CCITT_CRC(buff, 10);

	ptr = (char*)&crcv;
	sprintf(a, "%c%c", *ptr, *(ptr+1));
	sprintf(b, "%c", 0x7e);
	memcpy(buffer, buff, 10);
	sendb[0] = (char)0x7e;
	for(int j = 1; j < 11; j++)
		sendb[j] = buff[j-1];
	//free(buff);
	sendb[11] = (char)*ptr;
	sendb[12] = (char)*(ptr+1);	
	sendb[13] = (char) 0x7e;int gle;
	*a = (unsigned char)0x30; //*(a+1) = (unsigned char)0x32;
	sprintf(sendb, "%s%s%s%s", b, buff, a, b);
	CString dsend = CString(b)+ CString(buff) + CString(a) + CString(b);*/
	char dsend = char(a);//sendb);
	b[0] = 0x31;
	vptr = (unsigned char*)&b;

	
	if(!ConfigurePort(9600, 8, 0, NOPARITY, ONESTOPBIT))
	{
		printf("Cannot Configure Communication Port");
		getch();
		CloseHandle(hComm);
	}
	else
	{
	if(!SetCommunicationTimeouts(1000,1000,1000,1000,1000))
	{
		printf("Cannot Configure Communication Timeouts");
		getch();
		CloseHandle(hComm);
	}
	else
	{
	if(!WriteByte(&dsend))
	{
		printf("Cannot Write to Port");
		int gle = GetLastError();
		sprintf(err, "%x", gle);
		getch();
		CloseHandle(hComm);
	}
	else
	{
		sprintf(x, "%x",dsend);
		printf("Success%c",x);
		if(!ReadByte(&bw))
		printf("Timeout on getting Response.Please ensure that\nyou have connected the loop back plug to com1.");
	else 
	{
		memset(x, 0, 1);
		printf("Successfully Read from Com1");
		sprintf(x,"%x", bw);
		printf("Read Byte %c",x);
		getch();
		CloseHandle(hComm);
	}
	}
	}
	}
	}
0
oogabooga's Avatar
Ambitious contributor
It would be useful if you tell us where you got the bulk of the code from so we could see the original (which presumably works).

This looks wrong:
(LPCWSTR)"COM1"
Try this:
TEXT("COM1")

Also, your if/else if structure has more braces than necessary. This:
Code:
if()
{
}
else
{
  if()
  {
  }
  else
  {
    if()
    {
    }
    else
    {
      if()
      {
      }
      else 
      {
      }
    }
  }
}
Is usually written like this:
Code:
if()
{
}
else if()
{
}
else if()
{
}
else if()
{
}
else 
{
}
Or, since each if is testing for failure, it is even cleaner like this:
Code:
if (!FirstThing())
{
    ...
    exit (1);
}

if (!SecondThing())
{
    ...
    exit (2);
}

if (!ThirdThing())
{
    ...
    exit (3);
}

if (!FourthThing())
{
    ...
    exit (4);
}

// Success
...
return 0;
0
Cosmic_egg's Avatar, Join Date: Jul 2008
Go4Expert Member
According to the error number the error is communication port is not found....perhaps you could also try COM2 , COM3 , COM4 if the above solution does not work
you can also try below code
http://www.codeproject.com/KB/system/serial_com.aspx
0
Cosmic_egg's Avatar, Join Date: Jul 2008
Go4Expert Member
also try http://www.codeproject.com/KB/system/chaiyasit_t.aspx