If you are getting access denied error, chances are you have already opened the port, but then again I thought your CreateFile would fail. Double check your code to see if you are trying to open the file handle multiple times, and also make sure that your serial port file handle is still in scope and valid after splitting the source code up into files.
Below are pieces of a class I use for echoing serial data sent to the dev. board (minus my actual data handling.) Check to see if this gives you some hints.
the handleSerialData() function is supposed to be called repeatedly, polling for serial data.
If the code below leaves out something critical let me know and I'll send more info.
merry programming,
Andreas
class CSerialComms
{
public:
char m_serialString[20];
int m_serialRxCount;
int handleSerialData(CTargetDevice *chipCorder);
DCB m_dcb;
HANDLE m_hComPort;
CSerialComms();
virtual ~CSerialComms();
};
CSerialComms::CSerialComms()
{
m_hComPort = CreateFile(TEXT("COM3:"),
GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, 0, NULL);
m_dcb.DCBlength = sizeof(m_dcb);
GetCommState(m_hComPort, &m_dcb);
m_dcb.BaudRate = 115200;
m_dcb.fParity= FALSE;
m_dcb.fNull= FALSE;
m_dcb.StopBits = ONESTOPBIT;
m_dcb.Parity = NOPARITY;
m_dcb.ByteSize = 8;
SetCommState(m_hComPort, &m_dcb);
m_serialRxCount = 0;
}
CSerialComms::~CSerialComms()
{
CloseHandle(m_hComPort);
}
int CSerialComms::handleSerialData(CTargetDevice *chipCorder)
{
BYTE charTX;
DWORD countBytes;
int rxCount;
rxCount = ReadFile(m_hComPort, &charTX, 1, &countBytes, NULL);
if(countBytes != 0)
{
// echo serial data
rxCount = WriteFile(m_hComPort, &charTX, 1, &countBytes, NULL);
}
return 0;
}
|