串行通信

1.打开和关闭串行端口

和所有的流式设备一样,串行端口设备也使用CreateFile函数打开。所使用的名称要遵循特定的规范,即3个字符的COM后紧跟要打开的COM端口号,再几个冒号。冒号是WinCE所必须的,它是为了区别于在桌面版本的Windows系统中的设备驱动程序的命名规则。

传统的驱动程序命名规则中只允许有10个端口实例。WinCE也支持扩展的命名规则,这样就可以使用除了0--9以外的其他实例值。在这个命名规则中,驱动程序的前缀是“/$device/”,然后忽略掉末尾的冒号。如/$device/COM1 ,/$device/COM2 。

To open a serial port

  1. Insert a colon after the communication port pointed to with the first parameter, lpzPortName.

    For example, specify COM1: as the communication port.

  2. Specify zero in the dwShareMode parameter unless you a supported driver that allows multiple opens.

    Only one device can perform read/write or any operation that changes the behavior of the port. Other applications can perform operations such as port monitoring or controlling line status.

  3. Specify OPEN_EXISTING in the dwCreationDisposition parameter.

    This flag is required.

  4. Specify zero in the dwFlagsAndAttributes parameter.

    Windows CE supports only nonoverlapped I/O.

The following code example shows how to open a serial communications port.

// Open the serial port.
  hPort = CreateFile (lpszPortName, // Pointer to the name of the port
                      GENERIC_READ | GENERIC_WRITE,
                                    // Access (read-write) mode
                      0,            // Share mode
                      NULL,         // Pointer to the security attribute
                      OPEN_EXISTING,// How to open the serial port
                      0,            // Port attributes
                      NULL);        // Handle to port with attribute
                                    // to copy

Before writing to or reading from a port, configure the port.

When an application opens a port, it uses the default configuration settings, which might not be suitable for the device at the other end of the connection.

可以通过CloseHandle()函数来关闭一个串行设备端口。

2.读写串行端口

可以使用ReadFile和WriteFile来读写一个端口。

To read from a serial port
Pass the port handle to ReadFile in the hFile parameter.
The CreateFile function returns this handle when an application opens a port.
Specify a pointer to receive the data that is read in lpBuffer.
Specify the number of characters to read in nNumberOfBytesToRead.
Specify a pointer to a location where ReadFile will store the number of bytes read in lpNumberOfBytesRead.
Be sure that lpOverlapped is NULL.
Windows CE does not support overlapped I/O.
The following code example shows how to receive data using the ReadFile function.
BYTE Byte;
DWORD dwBytesTransferred;

ReadFile (hPort,                // Port handle
          &Byte,                // Pointer to data to read
          1,                    // Number of bytes to read
          &dwBytesTransferred,  // Pointer to number of bytes
                                // read
          NULL                  // Must be NULL for Windows CE
);

/

To write to a serial port
Pass the port handle to the WriteFile function in the hFile parameter.
The CreateFile function returns this handle when an application opens a port.
Specify a pointer to the data to be written in lpBuffer.
Often this data is binary data or a character array.
Specify the number of bytes to write in nNumberOfBytesToWrite.
The entire buffer can be passed to the driver.
Specify in lpNumberOfBytesWritten a pointer to a location where WriteFile will store the number of bytes actually written; then look at this location to determine if the data transferred.
Be sure that lpOverlapped is NULL.
The following code example shows how to transfer data using the WriteFile function.
DWORD dwError,
      dwNumBytesWritten;

WriteFile (hPort,              // Port handle
           &Byte,              // Pointer to the data to write
           1,                  // Number of bytes to write
           &dwNumBytesWritten, // Pointer to the number of bytes
                               // written
           NULL                // Must be NULL for Windows CE
);

 

///

你也可以通过下面的函数来发送单个字符:BOOL TransmitCommChar(HANDLE hFile,char cChar);TransmitCommChar和WriteFile函数的区别是TransmitCommChar将要传输的字符放在传输队列的前面。当你调用WriteFile时,字符将排队等候在还没有被串行设备驱动程序传输的任何字符之后。TransmitCommChar允许你快速的将控制字符插入到流中,而无需等待队列为空。

The TransmitCommChar function is useful for sending an interrupt character (such as a CTRL+C) to a host system.

If the device is not transmitting, TransmitCommChar cannot be called repeatedly.

After TransmitCommChar places a character in the output buffer, the character must be transmitted before the function can be called again.

If the previous character has not been sent, TransmitCommChar returns an error.

3.异步串行IO

WinCE还支持win32的WaitCommEvent函数,该函数将阻塞一个线程直到一个预先选择的串行事件发生。通过下面三个函数,你可以使线程等待串行驱动程序事件:

BOOL SetCommMask(HANDLE hFile,DWORD dwEventMask);

BOOL GetCommMask(HANDLE hFile,LPDWORD lpEventMask);

以及

BOOL WaitCommEvent(HANDLE hFile,LPWORD lpEvtMask,LPOVERLAPPED lpOverlapped);

要等待由SetCommMask指定的事件,应该调用WaitCommEvent。

下面的代码的作用是等待接收一个字符或等待一个错误。

DWORD dwMask;

SetCommMask(hcomPort,EV_RXCHAR | EV_ERR);

if(WaitCommEvent(hComPort,&dwMask,0))

{

//use the flags returned in dwMask to determine the reason

switch(dwMask)

{

case EV_RXCHAR:

//read char ;

break;

case EV_ERR:

//PROCESS WITH error

break;

}

}

 

4.配置串行端口

可以使用两个函数GetCommState()、SetCommState()来配置串口。

This function fills in a device-control block (a DCB structure) with the current control settings for a specified communication device.

BOOL GetCommState(
  HANDLE hFile, 
  LPDCB lpDCB
); 
Parameters
hFile
[in] Handle to the communication device.

The CreateFile function returns this handle.

lpDCB
[out] Long pointer to the DCB structure in which the control settings data is returned.
Return Values

Nonzero indicates success.

Zero indicates failure.

To obtain extended error data, call the GetLastError function.

///

This structure defines the control setting for a serial communications device.

typedef struct _DCB {
  DWORD DCBlength;
  DWORD BaudRate; 
  DWORD fBinary :1;
  DWORD fParity :1;
  DWORD fOutxCtsFlow :1;
  DWORD fOutxDsrFlow :1;
  DWORD fDtrControl :2;
  DWORD fDsrSensitivity :1;
  DWORD fTXContinueOnXoff :1;
  DWORD fOutX :1;
  DWORD fInX :1;
  DWORD fErrorChar :1;
  DWORD fNull :1; 
  DWORD fRtsControl :2; 
  DWORD fAbortOnError :1;
  DWORD fDummy2 :17;
  WORD wReserved;
  WORD XonLim; 
  WORD XoffLim;  
  BYTE ByteSize; 
  BYTE Parity; 
  BYTE StopBits;
  char XonChar; 
  char XoffChar; 
  char ErrorChar;
  char EofChar; 
  char EvtChar; 
  WORD wReserved1; 
} DCB, *LPDCB; 

 

This function configures a communications device according to specifications in a device-control block (DCB) structure.

The function reinitializes hardware and control settings, but does not empty output or input queues.

BOOL SetCommState(
  HANDLE hFile, 
  LPDCB lpDCB
); 
Parameters
hFile
[in] Handle to the communications device.

The CreateFile function returns this handle.

lpDCB
[in] Long pointer to a DCB structure containing the configuration information for the specified communications device.
Return Values

Nonzero indicates success.

Zero indicates failure.

To obtain extended error information, call the GetLastError function.

Remarks

The SetCommState function uses a DCB structure to specify the desired configuration. The GetCommState function returns the current configuration.

To set only a few members of the DCB structure, modify a DCB structure that has been filled in by a call to GetCommState. This ensures that other members of the DCB structure have appropriate values.

The SetCommState function fails if the XonChar member of the DCB structure is equal to the XoffChar member.

5.设置端口的超时值

超时是在ReadFile或WriteFile函数自动返回之前,wince等待读或写操作的时间长度。控制串口超时的函数是:GetCommTimeouts()、SetCommTimeouts();

BOOL GetCommTimeouts(
  HANDLE hFile, 
  LPCOMMTIMEOUTS lpCommTimeouts
); 
Parameters
hFile
[in] Handle to the communication device.

The CreateFile function returns this handle.

lpCommTimeouts
[out] Long pointer to a COMMTIMEOUTS structure in which the time-out data is returned.
Return Values

Nonzero indicates success.

Zero indicates failure.

To obtain extended error data, call the GetLastError function.

/

BOOL SetCommTimeouts(
  HANDLE hFile, 
  LPCOMMTIMEOUTS lpCommTimeouts
); 

/

The members determine the behavior of the ReadFile and WriteFile function operations on the device.

typedef struct _COMMTIMEOUTS { 
  DWORD ReadIntervalTimeout; //指定接收字符之间的最大间隔时间,0表示不用
  DWORD ReadTotalTimeoutMultiplier; //
  DWORD ReadTotalTimeoutConstant; 
  DWORD WriteTotalTimeoutMultiplier; 
  DWORD WriteTotalTimeoutConstant; 
} COMMTIMEOUTS,*LPCOMMTIMEOUTS; 
Members

//如果不管是否有数据要读取,希望Read函数立即返回:将ReadIntervalTimeout设置为MAXDWORD。将ReadTotalTimeoutMultiplierReadTotalTimeoutConstant设置为0。

//ReadFile函数没有是遏制超时值:即三个变量都为0,则直到有适当的字节数返回或者错误发生时,该函数才返回。

ReadIntervalTimeout
Specifies the maximum acceptable time, in milliseconds, to elapse between the arrival of two characters on the communication line.

In Windows CE, during a ReadFile operation, the time period begins immediately.

If the interval between the arrivals of two characters exceeds the time amount specified in ReadIntervalTimeout, the ReadFile operation is completed and buffered data is returned.

A value of zero indicates that interval timeouts are not used.

//ReadTotalTimeoutMultiplier*请求字符数+ReadTotalTimeoutConstant =Read函数超时总时间

ReadTotalTimeoutMultiplier
Specifies the multiplier, in milliseconds, used to calculate the total timeout period for read operations.

For each read operation, this value is multiplied by the requested number of bytes to be read.

ReadTotalTimeoutConstant
Specifies the constant, in milliseconds, used to calculate the total timeout period for read operations.

For each read operation, this value is added to the product of the ReadTotalTimeoutMultiplier member and the requested number of bytes.

A value of zero for the ReadTotalTimeoutMultiplier and ReadTotalTimeoutConstant members indicates that total timeouts are not used for read operations.

//WriteTotalTimeoutMultiplier*请求字符数+WriteTotalTimeoutConstant=Write函数超时总时间

WriteTotalTimeoutMultiplier
Specifies the multiplier, in milliseconds, used to calculate the total timeout period for write operations.

For each write operation, this value is multiplied by the number of bytes to be written.

WriteTotalTimeoutConstant
Specifies the constant, in milliseconds, used to calculate the total timeout period for write operations.

For each write operation, this value is added to the product of the WriteTotalTimeoutMultiplier member and the number of bytes to be written.

A value of zero for the WriteTotalTimeoutMultiplier and WriteTotalTimeoutConstant members indicates that total timeouts are not used for write operations.

Remarks

If an application sets ReadIntervalTimeout and ReadTotalTimeoutMultiplier to MAXDWORD and sets ReadTotalTimeoutConstant to a value greater than zero and less than MAXDWORD, one of the following occurs when the ReadFile function is called:

  • If there are characters in the input buffer, ReadFile returns immediately with the characters in the buffer.
  • If there are no characters in the input buffer, ReadFile waits until a character arrives and then returns immediately.
  • If no characters arrive within the time specified by ReadTotalTimeoutConstant, ReadFile times out.

 

/

还有一个SetupComm函数并不是很有用,他的原型为:

BOOL SetupComm(
  HANDLE hFile, 
  DWORD dwInQueue, 
  DWORD dwOutQueue
); 
Parameters
hFile
[in] Handle to the communications device.

The CreateFile function returns this handle.

dwInQueue
[in] Specifies the recommended size, in bytes, of the device's internal input buffer.
dwOutQueue
[in] Specifies the recommended size, in bytes, of the device's internal output buffer.
Return Values

Nonzero indicates success.

Zero indicates failure.

To obtain extended error information, call the GetLastError function.

6.查询串行驱动程序的能力

配置函数允许你配置串行驱动程序程序,但是因为串行驱动程序有各种不同的实现形式,所以在对其进行配置之前要知道他所支持的特性。函数GetCommProperties提供了这项服务。

BOOL GetCommProperties(
  HANDLE hFile, 
  LPCOMMPROP lpCommProp
); 
Parameters
hFile
[in] Handle to the communication device.

The CreateFile function returns this handle.

lpCommProp
[out] Long pointer to a COMMPROP structure in which the communication properties data is returned.

This data can be used in subsequent calls to the SetCommState, SetCommTimeouts, or SetupComm function to configure the communication device.

Return Values

Nonzero indicates success.

Zero indicates failure.

To obtain extended error data, call the GetLastError function.

///

This structure is used by the GetCommProperties function to return specific communication support driver data.

typedef struct _COMMPROP {
  WORD wPacketLength;
  WORD wPacketVersion;
  DWORD dwServiceMask;
  DWORD dwReserved1;
  DWORD dwMaxTxQueue;
  DWORD dwMaxRxQueue;
  DWORD dwMaxBaud;
  DWORD dwProvSubType;
  DWORD dwProvCapabilities;
  DWORD dwSettableParams;
  DWORD dwSettableBaud;
  WORD wSettableData;
  WORD wSettableStopParity;
  WORD dwCurrentTxQueue;
  DWORD dwCurrentRxQueue;
  DWORD dwProvSpec1;
  DWORD dwProvSpec2;
  WCHAR wcProvChar[1];
} COMMPROP;

 

7.控制串行端口

SetCommBreak(HANDLE hFile);

ClearCommBreak(HANDLE hFile);

This function suspends character transmission for a specified communications device and places the transmission line in a break state until the ClearCommBreak function is called.

BOOL SetCommBreak(
  HANDLE hFile
); 
///

This function restores character transmission for a specified communications device and places the transmission line in a nonbreak state.

BOOL ClearCommBreak(
  HANDLE hFile
); 

 

8.清除错误并查询状态

This function retrieves information about a communications error and reports the current status of a communications device.

The function is called when a communications error occurs, and it clears the error flag of the device to enable additional I/O operations.

BOOL ClearCommError(
  HANDLE hFile, 
  LPDWORD lpErrors, 
  LPCOMSTAT lpStat
); 
///

This function retrieves modem control-register values.

BOOL GetCommModemStatus(
  HANDLE hFile, 
  LPDWORD lpModemStat
); 
Parameters
hFile
[in] Handle to the communication device.

The CreateFile function returns this handle.

lpModemStat
[out] Long pointer to a 32-bit variable that specifies the current state of the modem control-register values.

The following are values for this parameter.

Value
Description

MS_CTS_ON
The CTS (Clear To Send) signal is on.

MS_DSR_ON
The DSR (Data Set Ready) signal is on.

MS_RING_ON
The ring indicator signal is on.

MS_RLSD_ON
The RLSD (Receive Line Signal Detect) signal is on.

Return Values

Nonzero indicates success.

Zero indicates failure.

To obtain extended error data, call the GetLastError function.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值