发布于 2005-12-23 20:43:40
0楼
传说中的高手说:利用低层API实现.在WIN32中所有的设备都被看成是文件,串行口也不例外,也是作为文件来进行处理的。实现串行通讯的步骤如下:打开串口、设置串口、监视串口事件、发送数据、接收数据和关闭串口。
1. 使用CreateFile()打开串口,CreateFile()将返回串口的句柄。
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: 指明串口制备,例:COM1,COM2
dwDesiredAccess: 指明串口存取方式,例:GENERIC_READ GENERIC_WRITE
dwShareMode: 指明串口共享方式
lpSecurityAttributes: 指明串口的安全属性结构,NULL为缺省安全属性
dwCreateionDistribution: 必须为:OPEN_EXISTIN
dwFlagAndAttributes: 对串口唯一有意义的是:FILE_FLAG_OVERLAPPED
hTemplatefile&: 必须为:NULL
例:
HANDLE m_hComm; // 串行设备句柄
UINT m_nPort; // 串口号
m_hComm = NULL;
m_nPort = 1;
CString strPort;
strPort.Format("\\\\.\\COM%d", m_nPort);
m_hComm = CreateFile(strPort,
GENERIC_READ GENERIC_WRITE, // 可读写
0, // 独占模式
NULL, // 缺省安全属性
OPEN_EXISTING, // 必须以已存在方式打开
FILE_FLAG_OVERLAPPED, // 异步I/O模式
NULL); // 必须为NULL
if (m_hComm == INVALID_HANDLE_VALUE)
{
// 打开串口失败
m_hComm = NULL;
return FALSE;
}
return TRUE;
2. 关闭串口:
CloseHandle(m_hComm);
3. 设置缓冲区长度:
BOOL SetupComm(
HANDLE hFile, // handle of communications device
DWORD dwInQueue, // size of input buffer
DWORD dwOutQueue // size of output buffer
);
例:
DWORD dwInQueue;
DWORD dwOutQueue;
dwInQueue = 4096;
dwOutQueue = 4096;
SetupComm(m_hComm, dwInQueue, dwOutQueue);
上面是一个高手的源码,可我怎么做都编译不成功。
革命多年,清风袖依然