The initialization of the COM Port looks like this:
- bool CSerial::Init(TCHAR *pszName, DWORD dwBaudrate)
- {
- bool retVal;
- m_hSPort = CreateFile( pszName,
- GENERIC_READ | GENERIC_WRITE,
- 0,
- NULL,
- OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED | FILE_FLAG_RANDOM_ACCESS,
- NULL
- );
- retVal = RS232Setting(dwBaudrate);
- return retVal;
- }
Display More
The settings look like this:
- bool CSerial::RS232Setting(DWORD dwBaudrate)
- {
- DCB PortDCB;
- //Initialize the DCBlength member.
- PortDCB.DCBlength = sizeof (DCB);
- //Get the default port setting information.
- GetCommState (m_hSPort, &PortDCB);
- //Change the DCB structure settings.
- PortDCB.BaudRate = dwBaudrate; //Current baud
- PortDCB.fBinary = TRUE; //Binary mode; no EOF check
- PortDCB.fParity = FALSE; //Enable parity checking
- PortDCB.fOutxCtsFlow = TRUE; //CTS output flow control
- PortDCB.fOutxDsrFlow = TRUE; //DSR output flow control
- PortDCB.fDtrControl = DTR_CONTROL_ENABLE; //DTR flow control type
- PortDCB.fDsrSensitivity = FALSE; //DSR sensitivity
- PortDCB.fTXContinueOnXoff = FALSE; //XOFF continues Tx
- PortDCB.fOutX = FALSE; //No XON/XOFF out flow control
- PortDCB.fInX = FALSE; //No XON/XOFF in flow control
- PortDCB.fErrorChar = FALSE; //Disable error replacement
- PortDCB.fNull = FALSE; //Disable null stripping
- PortDCB.fRtsControl = RTS_CONTROL_ENABLE;//RTS flow control
- PortDCB.fAbortOnError = FALSE; //Do not abort reads/writes on error
- PortDCB.ByteSize = 8; //Number of bits/byte, 4-8
- PortDCB.Parity = NOPARITY; //0-4=no,odd,even,mark,space
- PortDCB.StopBits = ONESTOPBIT; //0,1,2 = 1, 1.5, 2
- //Configure the port according to the specifications of the DCB structure.
- if (!SetCommState(m_hSPort, &PortDCB)) //Could not configure the serial port.
- {
- return FALSE;
- }
- return TRUE;
- }
Display More
This is more or less a copy of example code f&s delivers. The writing to the port looks like this:
- int CSerial::WriteFresh(BYTE bStream[], DWORD dwBytesToWrite)
- {
- //DWORD dwBytesTransferred;
- DWORD i;
- BYTE bDaten[510];
- for (i=0; i<dwBytesToWrite; i++)
- {
- bDaten[i] = *(bStream + i); //Übergabe der Daten an den Stream
- //Sleep(1);
- TransmitCommChar(m_hSPort, bDaten[i]);
- }
- //SetCommMask (m_hSPort, EV_RXCHAR); //Hier ein stopp gesetzt wird noch erreicht...
- //Sleep(1);
- //WriteFile (m_hSPort, &bDaten[0], 1, &dwBytesTransferred, NULL);
- return 1;//Dieser Punkt wird nie erreicht.
- }
Display More
Like already described ReadFile (..) works well, TransmitCommChar (..) like in the Code works well, too. Using the WriteFile (..) (like commented out) does not work. The line SetCommMask was just for some tryout, it does not work with or without that line. The program never leaves the WriteFile Routine.
The whole stuff works in an own thread.