2024年3月14日发(作者:)

Windows串口编程API函数

发表时间:2010-12-26 点击数:1232

·打开串口:

HANDLE CreateFile(

LPCTSTR lpFileName,

DWORD dwDesiredAccess,

DWORD dwShareMode,

LPSECURITY_ATTRIBUTES lpSecurityAttributes,

DWORD dwCreationDisposition,

DWORD dwFlagsAndAttributes,

HANDLE hTemplateFile

);

在Windows CE下,利用CreateFile函数打开一个COM口时,dwShareMode(共享模式)

必须设置为0,表示独占方式;lpSecurityAttributes(安全参数)必须设置为NULL;

hTemplateFile(模板文件)必须设置为NULL;dwCreationDisposition需要设置为

OPEN_EXISTING。则上述函数简化为:

HANDLE CreateFile(

LPCTSTR lpFileName,

DWORD dwDesiredAccess,

0,

NULL,

OPEN_EXISTING,

DWORD dwFlagsAndAttributes,

NULL

);

其中dwDesiredAccess设置为GENERIC_READ表示可读,设置为GENERIC_WRITE表

示可写。通常可通过如下示例打开一个串口。

CreateFile(

_T("COM1:"),

GENERIC_READ | GENERIC_WRITE, //允许读和写

0, //独占方式(共享模式)

NULL,

OPEN_EXISTING,

0,

NULL

);

打开串口成功,函数返回串口句柄;打开串口失败,函数返回INVALID_HANDLE_VALUE

·关闭串口:

BOOL CloseHandle(

HANDLE hObject

);

如:CloseHandle(m_hComm); //m_hComm是CreateFile函数返回的串口句柄。

关闭串口成功,函数返回非零值;关闭串口失败,函数返回零。

·DCB(设备控制块):

DCB结构完全描述了串口的使用参数。

typedef struct _DCB {

DWORD DCBlength; /* sizeof(DCB) */

DWORD BaudRate; /* Baudrate at which running */

DWORD fBinary: 1; /* Binary Mode (skip EOF check) */

DWORD fParity: 1; /* Enable parity checking */

DWORD fOutxCtsFlow:1; /* CTS handshaking on output */

DWORD fOutxDsrFlow:1; /* DSR handshaking on output */

DWORD fDtrControl:2; /* DTR Flow control */

DWORD fDsrSensitivity:1; /* DSR Sensitivity */

DWORD fTXContinueOnXoff: 1; /* Continue TX when Xoff sent */

DWORD fOutX: 1; /* Enable output X-ON/X-OFF */

DWORD fInX: 1; /* Enable input X-ON/X-OFF */

DWORD fErrorChar: 1; /* Enable Err Replacement */

DWORD fNull: 1; /* Enable Null stripping */

DWORD fRtsControl:2; /* Rts Flow control */

DWORD fAbortOnError:1; /* Abort all reads and writes on Error */

//打开而不是创建(创建方式)