VC serial communication routines Author: Ruan help autumn

zhaozj2021-02-11  230

VC serial communication routines Author: Ruan help autumn Published: 2001/04/19

Thesis:

The VC serial port communication program under the Win95 interface is not recommended to operate the port under Win32. All devices in Win32 are considered a file, and the serial port is not exception to be processed as a file. Key words serial port, dWord, buffer

text:

VC Implementation The VC Serial Port Communication program under the serial port communication routine WIN95 interface is not recommended to operate the port under Win32. All devices in Win32 are seen as a file, and the serial port is no exception is also used as a file. Treatment. This is my reading note on serial programming, which should have some help for peers programming with VC. 1. Open the serial port: The serial port is processed using the file operation in Window 95 as file processing. Use CreateFile () to open the serial port, createfile () will return the handle of the serial port. HANDLE CreateFile (LPCTSTR lpFileName, // pointer to name of the file DWORD dwDesiredAccess, // access (read-write) mode DWORD dwShareMode, // share mode LPSECURITY_ATTRIBUTES lpSecurityAttributes, // pointer to security attributes DWORD dwCreationDistribution, // how to create DWORD dwFlagsAndAttributes, // file attributes hANDLE hTemplateFile // handle to file with attributes to copy); lpFileName: preparation specified port, for example: COM1, COM2 dwDesiredAccess: indicates the serial access mode, for example: GENERIC_READ | GENERIC_WRITE dwShareMode: specified port sharing lpSecurityAttributes: security attributes specified serial structure, NULL default security attributes dwCreateionDistribution: must OPEN_EXISTIN dwFlagAndAttributes: serial port is only meaningful FILE_FLAG_OVERLAPPED hTemplateFile: serial port must be closed to NULL 2.: CloseHandle (hCommDev); 3. set buffer length: BOOL SetupComm (hANDLE hFile, // handle of communications device DWORD dwInQueue, // size of input buffer DWORD dwOutQueue // size of output buffer); 4.COMMPROP structures: may be used GetCommProperties () to obtain COMMPROP structure, the structure COMMPROP The various settings supported by the system are recorded.

typedef struct _COMMPROP {// cmmp WORD wPacketLength; // packet size, in bytes WORD wPacketVersion; // packet version DWORD dwServiceMask; // services implemented DWORD dwReserved1; // reserved DWORD dwMaxTxQueue; // max Tx bufsize, in bytes DWORD dwMaxRxQueue ; // max Rx bufsize, in bytes DWORD dwMaxBaud; // max baud rate, in bps DWORD dwProvSubType; // specific provider type DWORD dwProvCapabilities; // capabilities supported DWORD dwSettableParams; // changeable parameters DWORD dwSettableBaud; // allowable baud rates WORD wSettableData; // allowable byte sizes WORD wSettableStopParity; // stop bits / parity allowed DWORD dwCurrentTxQueue; // Tx buffer size, in bytes DWORD dwCurrentRxQueue; // Rx buffer size, in bytes DWORD dwProvSpec1; // provider-specific data DWORD DWPROVSPEC2; // provider-specific data wchar wcrovchar [1]; // provider-specific Data} CommProp; dwmaxbaud: baud_075 75 bps baud_110 110 bps baud_134_5 134.5 bps baud_150 150 bps BAUD_300 300 bps BAUD_600 600 bps BAUD_1200 1200 bps BAUD_1800 1800 bps BAUD_2400 2400 bps BAUD_4800 4800 bps BAUD_7200 7200 bps BAUD_9600 9600 bps BAUD_14400 14400 bps BAUD_19200 19200 bps BAUD_38400 38400 bps BAUD_56K 56K bps BAUD_57600 57600 bps BAUD_115200 115200 bps BAUD_128K 128K bps BAUD_USER Programmable baud Rates Available DWPROVSUBTYPE:

PST_FAX facsimile apparatus PST_LAT LAT protocol PST_MODEM PST_NETWORK_BRIDGE modem device not designated bridge PST_PARALLELPORT parallel PST_RS232 RS-232 port PST_RS422 RS-422 port PST_RS423 RS-432 port PST_RS449 RS-449 port PST_SCANNER scanner device PST_TCPIP_TELNET TCP / IP Telnet protocol is not specified PST_UNSPECIFIED PST_X25 X.25 standard dwProvCapabilities PCF_16BITMODE supports special 16-bit mode PCF_DTRDSR support the DTR (data terminal ready) / DSR (data Set ready) PCF_INTTIMEOUTS support timeout interval PCF_PARITY_CHECK support parity PCF_RLSD support RLSD (received line signal detector) PCF_RTSCTS support RTS ( Request Send) / CTS (Clear Send) PCF_SETXCHAR Support Settable XON / XOFF PCF_SPECIALCHARS Support Special Character PCF_TOTALTIMEOUTS Support Total (Time) Timeout PCF_XONXOFF Support XON / XOFF Standard RS-232 and Window Support All PCF_16BitMode and PCF_SPECIALCHAR Function DWSETTABLEPARAMS SP_BAUD Configurable Potter Rate SP_DATABITS Configurable Data Base SP_Handshaking Configurable Handshake (Flow Control) SP_Parity Configurable Parity Sample SP_PARITY_CHECK Configurable Parity Allow / Disable SP_RLSD Configuring RLSD (Receive Signal Detection) SPBITS Configuring Stop Bit Number RS-232 and Window Support All Functions WsettableData DataBits_5 5 Data Bit Database_6 6 Data Bit Database_7 7 Data Bits Database_8 8 Data Bit Database_16 16 Data Bits Database_16X Via Serial Hardware Line Special Wide Degree path Windows 95 supports all settings 5.dcb structure: typedef struct _dcb {// DCB DWORD DCBLENGTH; // SizeOf (DCB) DWORD Baudrate; // Current Baud Rate Specifies the current baud rate DWORD FBINARY: 1; / / Binary Mode, No EOF Check Specifies whether to allow binary mode, Windows 95 must be true dword fparity: 1; // enable parity checking specifies whether dword foutxctsflow: 1; // CTS Output Flow Control Specify whether CTS is used Detected transmission control. When True is CTS is OFF, the transmission will be suspended. DWORD FoutxDSRFlow: 1; // DSR OUTPUT FLOW Control Specifies whether the CTS is used to detect send control. When True is CTS is OFF, the transmission will be suspended.

DWORD fDtrControl: 2; // DTR flow control DTR_CONTROL_DISABLE the DTR value of the type set OFF, DTR_CONTROL_ENABLE DTR value set ON, DTR_CONTROL_HANDSHAKE allows DTR "handshake", DWORD fDsrSensitivity: 1; // DSR sensitivity when the value TRUE when the DSR The bytes received for OFF are ignored DWORD ftxcontinueonxoff: 1; // Xoff Continues TX Specifies whether the transmit buffer is full and the driver has been sent to the Xoffchar characters. When True, the transmitted buffer receives the byte Xofflim that is full of the buffer, and the driver has sent the XoffChar character aborted byte, the transmission continues. When FALSE, the transmitted buffer receives the byte xonchar that represents the buffer has empty and the driver has sent the Xonchar that has been resumed.

DWORD Foutx: 1; // XON / XOFF OUT FLOW Control True, after receiving Xoffchar, stop sending the XONCHAR will restart DWORD FINX: 1; // XON / XOFF in Flow Control True, receive buffer reception After the Xofflim represents the buffer area, XOFFCHAR sends out the reception buffer to receive Xonlim that represents the empty space, XONCHAR sends the dword ferrorchar: 1; // enable Error Replacement This value is true and fparity is True, using errorchar Members specified by the character replace the parity error: 1; // enable null stripping true, when receiving the empty (0 value) byte DWORD FRTSCONTSCONTROL: 2; // RTS Flow Control RTS_CONTROL_DISABLE, RTS When the RTS_Control_enable, RTS is set to ON RTS_CONTROL_HANDSHAKE, when the received buffer is less than half full, the RTS is ON when the receiving buffer exceeds three-quarters, when the RTS is OFF RTS_CONTROL_TOGGLE, when there is still the remaining byte of the receiving buffer RTS is ON, otherwise the default is OFF DWORD FABORTONERROR: 1; // Abort Reads / Writes On Error True, there is an error occurred and written during the inter-read and write operation DWORD fdummy2: 17; // reserved unused Word Wreserved; // not Currently Used unused, must be 0 word xonlim; // transmit xon threshold Specifies the number of least bytes that can be allowed in this pre-receiving buffer in the XON character; // transmit Xoff threshold specifies that the Xoff characters are sent before receiving this The minimum byte of the buffer can be allowed byte bytesize; // Number of bits / byte, 4-8 Specify the data bit currently used by the port BYT E parity; // 0-4 = NO, ODD, EVEN, MARK, SPACE Specifies the parity method for the currently used by: EvenParity, MarkParity, Noparity, Oddparity Byte Stopbits; // 0, 1, 2 = 1 1.5, 2 Specify the number of stop bits currently used by the port, may be: onestopbit, one5stopbits, twostopbits char xonchar; // tx and rx xon character Specifies the value of the value for sending and receiving character xon; // tx and rx xoff CHARACTER specifies the value of the value of Char EOFCHAR for transmitting and receiving character Xoff value CHAR ERRORCHAR; // error Replacement Character This character is used instead of the received parity; // end of input character When there is no binary mode, This character can be used to indicate the end of the data. CHAR EVTCHAR; // Received Event Character generates an event word Wreserved1; // reserved; Do Not Use is not used} DCB; 6. Change port settings are used Two Method Bool Getcommstate (HCOMM, & DCB); Bool Setcommstate (HCOMM, &

DCB); 7. Change the normal setting buildcommdcb (SZSettings, & DCB); SZSETTINGS format: Baud Parity Data Stop Example: "BAUD = 96 Parity = N DATA = 8 STOP = 1" Shop: "96, n, 8, 1" Valid value of SZSettings BAUD: 11 or 110 = 110 BPS 15 or 150 = 150 BPS 30 or 300 = 300 BPS 60 OR 600 = 600 BPS 12 or 1200 = 1200 BPS 24 or 2400 = 2400 bps 48 or 4800 = 4800 bps 96 OR 9600 = 9600 BPS 19 or 19200 = 19200bps parity: n = none e = Even o = odd m = mark s = space data: 5, 6, 7, 8 stopbit 1, 1.5, 2 8.commconfig structure: typedef struct _comm_config { DWORD dwSize; WORD wVersion; WORD wReserved; DCB dcb; DWORD dwProviderSubType; DWORD dwProviderOffset; DWORD dwProviderSize; WCHAR wcProviderData [1];} COMMCONFIG, * LPCOMMCONFIG; may be convenient to use BOOL CommConfigDialog (LPTSTR lpszName, HWND hWnd, LPCOMMCONFIG lpCC); To set the serial port.

9. timeout settings: COMMTIMEOUTS structure may be provided by a timeout, typedef struct _COMMTIMEOUTS {DWORD ReadIntervalTimeout; DWORD ReadTotalTimeoutMultiplier; DWORD ReadTotalTimeoutConstant; DWORD WriteTotalTimeoutMultiplier; DWORD WriteTotalTimeoutConstant;} COMMTIMEOUTS, * LPCOMMTIMEOUTS; timeout interval :( only useful in data read from the port It specifies that the time time for the time to read between the two characters: When the total time required to read or write a specific byte exceeds a certain threshold, timeout trigger. Timeout formula: readtotalTimeout = (ReadtotalTimeoutMultiplier * Bytes_to_read) ReadToTaltimeoutConstant WriteTotalTimeout = (WriteTotalTimeoutMuliplier * bytes_to_write) WritetoTotalTimeoutConstant NOTE: parameter 0 when setting the timeout wait indefinitely, neither the timeout parameter MAXDWORD is immediately returned timeout settings: GetCommTimeouts (hComm, & timeouts); SetCommTimeouts (hComm, & timeouts); 10. read and write data query routine: COMMTIMEOUTS to; DWORD ReadThread (LPDWORD lpdwParam) {BYTE inbuff [100]; DWORD nBytesRead; if ((cp.dwProvCapabilities & PCF_INTTIMEOUTS)!) return 1L; memset (& to, 0, sizeof (to)) RREADINTERVALTIMEOUT = MaxDword; setcommtimeouts (hcomm, & to); while (break) {if (! Readfile (hcomm, inbuff, 100, & nBytesRead, NULL)) locProcessCommError (GetLastError ()); else if (nBytesRead) locProcessBytes (inbuff, nBytesRead);} PurgeComm (hComm, PURGE_RXCLEAR); return 0L;} NOTE: PurgeComm () is a clear function, it can Any unreasonable background read or written, and can be rushed off. Bool PurgeComm (Handle Hfile, DWORD DWFLAGS); DWFlags Valid: Purge_txabort: Aborted Background Write Procedure PRUGE_RXABORT: Stop Operation PRUGE_TXCLEAR: Clear Send Buffer Prurance_Rxclear: Clear Receive Burch Tips: You can determine the number of bytes in the receiving mematic in the receiving mematic.

BOOL ClearCommError (HANDLE hFile, // handle to communications device LPDWORD lpErrors, // pointer to variable to receive error codes LPCOMSTAT lpStat // pointer to buffer for communications status); ClearCommError () will return a COMSTAT structure: typedef struct _COMSTAT {/ / cst dword fctshold: 1; // TX Waiting for CTS Signal DWORD FDSRHOLD: 1; // TX Waiting for DSR Signal DWORD FXOFFHOLD: 1; // TX WAITING, Xoff Char Rec`d dword fxoffsent: 1; // TX Waiting, Xoff Char Sent DWord Feof: 1; // Eof Character Sent Dword FTXIM: 1; // Character Waiting for TX DWORD FRESERVED: 25; // RESERVED DWORD CBINQUE; // BYtes in Input Buffer DWORD CBOUTQUE; // Bytes in Output Buffer} Comst, * lpComstat; in the cbinQue and CBoutQue are buffer bytes.

11. A synchronous I / O read and write data COMMTIOMOUTS to; DWORD ReadThread (LPDWORD lpdwParam) {BYTE inbuff [100]; DWORD nByteRead, dwErrorMask, nToRead; COMSTAT comstat; if (cp.dwProvCapabilities & PCF_TOTALTIMEOUTS!) Return 1L; memset (& to, 0 , sizeof (to)); to.ReadTotalTimeoutMultiplier = 5; to.ReadTotalTimeoutConstant = 50; SetCommTimeouts (hComm, & to); while (bReading) {ClearCommError (hComm, & dwErrorMask, & comstat); if (dwErrorMask) locProcessCommError (dwErrorMask); if (Comstat.cbinque> 100) NTOREAD = 100; Else Ntoread = Comstat.cbinque; if (ntoread == 0) Continue; if (! Readfile (HCOMM, INBUFF, NTOREAD, & NBYTESREAD, NULL)) LocProcessCommorror (GetLastError ()); Else if (NbytesRead);} return 0l;} 12. Asynchronous I / O Read and write data When the fdwattrsandflags parameter in CreateFile () is file_flag_overlappen, the port is opened for asynchronous I / O, at this time A Overlapped structure can be specified in the last parameter of the ReadFile, making the read operation of the data in the background. Windows 95 includes many variants of asynchronous I / O. Typedef struct _over; dword; dword; dword;} overlapped; only HEVENT member is valid for serial ports, it must be 0.

Routine: COMMTIMEOUTS to; ... DWORD ReadThread ((LPDWORD lpdwParam) {BYTE inbuff [100]; DWORD nRytesRead, endtime, lrc; static OVERLAPPED o; if (cp.dwProvCapabilities & PCF_TOTALTIMEOUTS) return 1L; memset (& to,! 0, sizeof (to)); to.ReadTotalTimeoutMultiplier = 5; to.ReadTotalTimeoutConstant = 1000; SetCommTimeouts (hComm, & to); o.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL); while (bReading) {if (! ReadFile (hComm, inbuff, 10, & nBytesRead, & o)) {nBytesRead = 0; if (lrc = GetLastError () == ERROR_IO_PENDING) {endtime = GetTickCount () 1000; while (GetOverlappedResult (hComm, & o, & nBytesRead, FALSE! )) if (GetTickCount ()> endtime) break;} if (nBytesRead) locProcessBytes (inbuff, nBytesRead);} else {if (nBytesRead) locProcessBytes (inbuff, nBytesRead); ResetEvent (o.hEvent);}} PurgeComm (hComm , Purge_rxclear; return 0L;} This routine is the process of reading the desired byte for the first reading buffer: while (break) {if (! Readfile (hcomm, inbuff, 10, & nbytesread, & o) ) {IF ((LRC = getLastError ()) = = ERROR_IO_PENDING) {if (GetOverlappedResult (hComm, & o, & nBytesRead, TRUE)) {if (nBytesRead) locProcessBytesa (inbuff, nBytesRead);} else locProcessCommError (GetLastError ());} else locProcessCommError (GetLastError));} else if ( NbytesRead) (Inbuff, NbytesRead); resetEvent (O.hevent);} 13. Event Drive I / O Read and Write: getcommmask (HCOMM, & DWMASK) Windows 95 Reports Events reported to the application Returns. SetCommmasl (HCOMM, & DWMASK) adds or modifies the list of events reported by Windows 95.

The event mask is as follows: EV_BREAK detects that the EV_CTS CTS signal change state EV_DSR DSR (data setting ready) signal change state EV_ERR has a line state error. Line status error is: CE_FRAME (frame error) CE_OVERRUN (Receive buffer) Overrun limit) CE_RXPARITY EV_RING Detects Ring EV_RLSD RLSD (Receive Line Signal Detection) Signal Change Status EV_EXCHAR Receives a character and puts the input buffer EV_RXFLAG to receive event characters (Evtchar members of DCB members) ), The last character sent in the input buffer EV_TXEMPTY output buffer is sent out after specifying a useful event with setcommmask, the application can call Waitcommevent () to wait for the event. Bool Waitcommevent (Handle Hfile, // Handle of) communications device LPDWORD lpEvtMask, // address of variable for event that occurred LPOVERLAPPED lpOverlapped, // address of overlapped structure); this method may be synchronous or asynchronous mode operation routine: COMMTIMEOUTS to; ... DWORD ReadTherad (LPDWORD lpdwParam) { BYTE binbuff [100]; DWORD nBytesRead, dwEvent, dwError; COMSTAT cs; SetCommMask (hComm, EV_RXHAR); while (bReading) {if (WaitCommEvent (hComm, & dwEvent, NULL)) {ClearCommError (hComm, & dwError, & cs); if ((DWEVENT & EV_RXCHAR) && cs.cbinque) {if (! Readfile (hcomm, inbuff, cs.cbinque, & nbytesread, null) LocProcesscom mError (GetLastError ());} else {if (nByteRead) locProcessBytes (inbuff, nBytesRead);} else locProcessCommError (GetLastError ());} PurgeComm (hComm, PURGE_RXCLEAR); return 0L;} NOTE: SetCommMask (hComm, 0) . make the WaitCommEvent () to suspend use GetCommModemStatus () method routines: if (cp.dwProvCapabilities & PCF_RTSCTS) {SetCommMask (hComm, EV_CTS); WaitCommEvent (hComm, & dwMask, NULL); if (dwMask & EV_CTS) {GetCommModemStatus (hComm, & dwStatus ) / * Ctstatus & ms_CTS_ON) / * CTS stransition off-on * / else / * CTS stransition on-off * /}} ms_cts_on CTS is ON ms_dsr_on dsr is ON ms_ring_on ring to ON ms_lsd_on rlsd is ON 14. Error When an error occurs Method Clearcommorror (HCOMM, & DWERRORSK, & & D)

转载请注明原文地址:https://www.9cbs.com/read-5003.html

New Post(0)