HANDLE CreateFile ( LPCTSTR lpFileName, //将要打开的串口逻辑名,如COM1 或COM2 DWORD dwAccess, //指定串口访问的类型,可以是读取、写入或两者并列 DWORD dwShareMode, //指定共享属性,由于串口不能共享,该参数必须置为0 LPSECURITY_ATTRIBUTES lpsa, //引用安全性属性结构,缺省值为NULL DWORD dwCreate, //创建标志,对串口操作该参数必须置为OPEN EXISTING DWORD dwAttrsAndFlags, //属性描述,用于指定该串口是否可进行异步操作, //FILE_FLAG_OVERLAPPED:可使用异步的I/O HANDLE hTemplateFile //指向模板文件的句柄,对串口而言该参数必须置为NULL ); |
HANDLE hCom; DWORD dwError; hCon = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hCom == (HANDLE)0xFFFFFFFF) { dwError = GetLastError(); MessageBox(dwError); } |
typedef struct _DCB { // dcb DWORD DCBlength; // sizeof(DCB) DWORD BaudRate; // current baud rate DWORD fBinary: 1; // binary mode, no EOF check DWORD fParity: 1; // enable parity checking DWORD fOutxCtsFlow:1; // CTS output flow control DWORD fOutxDsrFlow:1; // DSR output flow control DWORD fDtrControl:2; // DTR flow control type DWORD fDsrSensitivity:1; // DSR sensitivity DWORD fTXContinueOnXoff:1; // XOFF continues Tx DWORD fOutX: 1; // XON/XOFF out flow control DWORD fInX: 1; // XON/XOFF in flow control DWORD fErrorChar: 1; // enable error replacement DWORD fNull: 1; // enable null stripping DWORD fRtsControl:2; // RTS flow control DWORD fAbortOnError:1; // abort reads/writes on error DWORD fDummy2:17; // reserved WORD wReserved; // not currently used WORD XonLim; // transmit XON threshold WORD XoffLim; // transmit XOFF threshold BYTE ByteSize; // number of bits/byte, 4-8 BYTE Parity; // 0-4=no,odd,even,mark,space BYTE StopBits; // 0,1,2 = 1, 1.5, 2 char XonChar; // Tx and Rx XON character char XoffChar; // Tx and Rx XOFF character char ErrorChar; // error replacement character char EofChar; // end of input character char EvtChar; // received event character WORD wReserved1; // reserved; do not use } DCB; 而SetupComm函数的原型则为: BOOL SetupComm( HANDLE hFile, // handle to communications device DWORD dwInQueue, // size of input buffer DWORD dwOutQueue // size of output buffer ); |
DCB dcb; dcb.BaudRate = 9600; //波特率为9600 dcb.ByteSize = 7; //数据位数为7位 dcb.Parity = EVENPARITY; //偶校验 dcb.StopBits = 2; //两个停止位 dcb.fBinary = TRUE; dcb.fParity = TRUE; if (!SetCommState(hCom, &dcb)) { MessageBox("串口设置出错!"); } SetupComm(hCom, 1024, 1024); PurgeComm(hCom, PURCE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); |
typedef struct _COMMTIMEOUTS { DWORD ReadIntervalTimeout; //定义两个字符到达的最大时间间隔,单位:毫秒 //当读取完一个字符后,超过了ReadIntervalTimeout,仍未读取到下一个字符,就会 //发生超时 DWORD ReadTotalTimeoutMultiplier; DWORD ReadTotalTimeoutConstant; //其中各时间所满足的关系如下: //ReadTotalTimeout = ReadTotalTimeOutMultiplier* BytesToRead + ReadTotalTimeoutConstant DWORD WriteTotalTimeoutMultiplier; DWORD WriteTotalTimeoutConstant; } COMMTIMEOUTS, *LPCOMMTIMEOUTS; |
BOOL SetCommTimeouts( HANDLE hFile, // handle to communications device LPCOMMTIMEOUTS lpCommTimeouts // pointer to comm time-out structure ); |
COMMTIMEOUTS to; memset(&to, 0, sizeof(to)); to.ReadIntervalTimeout = 10; SetCommTimeouts(hCom, &to); |
BOOL GetCommTimeouts( HANDLE hFile, // handle of communications device LPCOMMTIMEOUTS lpCommTimeouts // pointer to comm time-out structure ); |
BOOL SetCommMask( HANDLE hFile, //标识通信端口的句柄 DWORD dwEvtMask //能够使能的通信事件 ); |
BOOL GetCommMask( HANDLE hFile, //标识通信端口的句柄 LPDWORD lpEvtMask // address of variable to get event mask ); |
BOOL WaitCommEvent( HANDLE hFile, //标识通信端口的句柄 LPDWORD lpEvtMask, // address of variable for event that occurred LPOVERLAPPED lpOverlapped, // address of overlapped structure ); |
BOOL ReadFile( HANDLE hFile, // handle of file to read LPVOID lpBuffer, // pointer to buffer that receives data DWORD nNumberOfBytesToRead, // number of bytes to read LPDWORD lpNumberOfBytesRead, // pointer to number of bytes read LPOVERLAPPED lpOverlapped // pointer to structure for overlapped I/O ); |
BOOL WriteFile( HANDLE hFile, // handle to file to write to LPCVOID lpBuffer, // pointer to data to write to file DWORD nNumberOfBytesToWrite, // number of bytes to write LPDWORD lpNumberOfBytesWritten, // pointer to number of bytes written LPOVERLAPPED lpOverlapped // pointer to structure for overlapped I/O ); |
BOOL CloseHandle( HANDLE hObject // handle to object to close ); |
2.例程
在笔者的《深入浅出Win32多线程程序设计之综合实例》中我们已经给出一个利用WIN API进行串口通信的例子,这里再给出一个类似的例子,以进一步加深理解。
利用WIN API进行串口通信
|
BEGIN EDITTEXT IDC_RECV_EDIT,28,119,256,46,ES_AUTOHSCROLL GROUPBOX "发送数据",IDC_STATIC,19,15,282,70 GROUPBOX "接收数据",IDC_STATIC,19,100,282,80 EDITTEXT IDC_SEND_EDIT,29,33,214,39,ES_AUTOHSCROLL PUSHBUTTON "清除",IDC_CLEAR_BUTTON,248,33,50,14 PUSHBUTTON "发送",IDC_SEND_BUTTON,248,55,50,14 END |
BEGIN_MESSAGE_MAP(CSerialPortAPIDlg, CDialog) //{{AFX_MSG_MAP(CSerialPortAPIDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_CLEAR_BUTTON, OnClearButton) ON_BN_CLICKED(IDC_SEND_BUTTON, OnSendButton) ON_MESSAGE(COM_RECVDATA, OnRecvData) //}}AFX_MSG_MAP END_MESSAGE_MAP() |
class CSerialPortAPIDlg : public CDialog { // Construction public: CSerialPortAPIDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CSerialPortAPIDlg) enum { IDD = IDD_SERIALPORTAPI_DIALOG }; CString m_recv; //IDC_RECV_EDIT控件对应的变量 CString m_send; //IDC_SEND_EDIT控件对应的变量 //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSerialPortAPIDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: BOOL OpenSerialPort1(); HICON m_hIcon; // Generated message map functions //{{AFX_MSG(CSerialPortAPIDlg) virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnClearButton(); afx_msg void OnSendButton(); afx_msg void OnRecvData(WPARAM wParam, LPARAM lParam); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CSerialPortAPIDlg::CSerialPortAPIDlg(CWnd* pParent /*=NULL*/) : CDialog(CSerialPortAPIDlg::IDD, pParent) { //{{AFX_DATA_INIT(CSerialPortAPIDlg) //在构造函数中初始化变量 m_recv = _T(""); //在构造函数中初始化变量 m_send = _T(""); //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } //建立编辑框控件和变量之间的映射 void CSerialPortAPIDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CSerialPortAPIDlg) DDX_Text(pDX, IDC_RECV_EDIT, m_recv); DDX_Text(pDX, IDC_SEND_EDIT, m_send); //}}AFX_DATA_MAP } |
BOOL CSerialPortAPIDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here //启动串口监视线程 DWORD threadID; hCommThread = ::CreateThread((LPSECURITY_ATTRIBUTES)NULL, 0, (LPTHREAD_START_ROUTINE)SerialPort1ThreadProcess, AfxGetMainWnd()->m_hWnd, 0, &threadID); if (hCommThread == NULL) { ::AfxMessageBox("创建串口1处理线程失败"); ::PostQuitMessage(0); } return TRUE; // return TRUE unless you set the focus to a control } //"清除"按钮函数 void CSerialPortAPIDlg::OnClearButton() { // TODO: Add your control notification handler code here m_send = ""; UpdateData(false); } //发送数据函数("发送"按钮函数) void CSerialPortAPIDlg::OnSendButton() { // TODO: Add your control notification handler code here UpdateData(true); DWORD wCount = 0; WriteFile(hCom, m_send, m_send.GetLength(), &wCount, NULL);//发送数据 } //接收数据后(通过监听线程发来的用户自定义消息)显示 void CSerialPortAPIDlg::OnRecvData(WPARAM wParam, LPARAM lParam) { CString recvStr((char *)wParam); m_recv += recvStr; UpdateData(false); } |
#ifndef _SERIAL_PORT_CONTROL_H #define _SERIAL_PORT_CONTROL_H #define COM_RECVDATA WM_USER+1000//自定义消息 extern HANDLE hCom; //全局变量,串口句柄 extern HANDLE hCommThread; //全局变量,串口线程 //串口监视线程控制函数 extern DWORD WINAPI SerialPort1ThreadProcess(HWND hWnd); //打开并设置PC串口1(COM1) extern BOOL OpenSerialPort1(); #endif SerialPortControl.cpp文件 #include "StdAfx.h" #include "SerialPortControl.h" HANDLE hCom; //全局变量,串口句柄 HANDLE hCommThread; //全局变量,串口线程 BOOL OpenSerialPort1() { //打开并设置COM1 hCom=CreateFile("COM1", GENERIC_READ|GENERIC_WRITE, 0,NULL , OPEN_EXISTING, 0, NULL); if (hCom==(HANDLE)-1) { AfxMessageBox("打开COM1失败"); return false; } else { DCB wdcb; GetCommState (hCom, &wdcb); wdcb.BaudRate=9600;//波特率:9600,其他:不变 SetCommState (hCom, &wdcb); PurgeComm(hCom, PURGE_TXCLEAR); } return true; } //以一个线程不同监控串口行接收的数据 DWORD WINAPI SerialPort1ThreadProcess( HWND hWnd//主窗口句柄) { char str[101]; DWORD wCount; //读取的字节数 while(1) { ReadFile(hCom,str, 100, &wCount, NULL); if(wCount > 0) //收到数据 { str[wCount] = '/0'; ::PostMessage(hWnd, COM_RECVDATA, (unsigned int) str, wCount); //发送消息给对话框主窗口,以进行接收内容的显示 } } return TRUE; } |
显示本程序工作正确,发送和接收字符准确无误