HANDLE CreateFile ( LPCTSTR lpFileName, //將要打開的串口邏輯名,如COM1 或COM2 DWORD dwAccess, //指定串口訪問的類型,可以是讀取、寫入或兩者并列 DWORD dwShareMode, //指定共享屬性,由于串口不能共享,該參數(shù)必須置為0 LPSECURITY_ATTRIBUTES lpsa, //引用安全性屬性結(jié)構(gòu),缺省值為NULL DWORD dwCreate, //創(chuàng)建標(biāo)志,對串口操作該參數(shù)必須置為OPEN EXISTING DWORD dwAttrsAndFlags, //屬性描述,用于指定該串口是否可進(jìn)行異步操作, //FILE_FLAG_OVERLAPPED:可使用異步的I/O HANDLE hTemplateFile //指向模板文件的句柄,對串口而言該參數(shù)必須置為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函數(shù)的原型則為: 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; //數(shù)據(jù)位數(shù)為7位 dcb.Parity = EVENPARITY; //偶校驗(yàn) dcb.StopBits = 2; //兩個(gè)停止位 dcb.fBinary = TRUE; dcb.fParity = TRUE; if (!SetCommState(hCom, &dcb)) { MessageBox("串口設(shè)置出錯(cuò)!"); } SetupComm(hCom, 1024, 1024); PurgeComm(hCom, PURCE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); |
typedef struct _COMMTIMEOUTS { DWORD ReadIntervalTimeout; //定義兩個(gè)字符到達(dá)的最大時(shí)間間隔,單位:毫秒 //當(dāng)讀取完一個(gè)字符后,超過了ReadIntervalTimeout,仍未讀取到下一個(gè)字符,就會 //發(fā)生超時(shí) DWORD ReadTotalTimeoutMultiplier; DWORD ReadTotalTimeoutConstant; //其中各時(shí)間所滿足的關(guān)系如下: //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, //標(biāo)識通信端口的句柄 DWORD dwEvtMask //能夠使能的通信事件 ); |
BOOL GetCommMask( HANDLE hFile, //標(biāo)識通信端口的句柄 LPDWORD lpEvtMask // address of variable to get event mask ); |
BOOL WaitCommEvent( HANDLE hFile, //標(biāo)識通信端口的句柄 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 ); |
![]() |
BEGIN EDITTEXT IDC_RECV_EDIT,28,119,256,46,ES_AUTOHSCROLL GROUPBOX "發(fā)送數(shù)據(jù)",IDC_STATIC,19,15,282,70 GROUPBOX "接收數(shù)據(jù)",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 "發(fā)送",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控件對應(yīng)的變量 CString m_send; //IDC_SEND_EDIT控件對應(yīng)的變量 //}}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) //在構(gòu)造函數(shù)中初始化變量 m_recv = _T(""); //在構(gòu)造函數(shù)中初始化變量 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 //啟動(dòng)串口監(jiān)視線程 DWORD threadID; hCommThread = ::CreateThread((LPSECURITY_ATTRIBUTES)NULL, 0, (LPTHREAD_START_ROUTINE)SerialPort1ThreadProcess, AfxGetMainWnd()->m_hWnd, 0, &threadID); if (hCommThread == NULL) { ::AfxMessageBox("創(chuàng)建串口1處理線程失敗"); ::PostQuitMessage(0); } return TRUE; // return TRUE unless you set the focus to a control } //"清除"按鈕函數(shù) void CSerialPortAPIDlg::OnClearButton() { // TODO: Add your control notification handler code here m_send = ""; UpdateData(false); } //發(fā)送數(shù)據(jù)函數(shù)("發(fā)送"按鈕函數(shù)) 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);//發(fā)送數(shù)據(jù) } //接收數(shù)據(jù)后(通過監(jiān)聽線程發(fā)來的用戶自定義消息)顯示 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; //全局變量,串口線程 //串口監(jiān)視線程控制函數(shù) extern DWORD WINAPI SerialPort1ThreadProcess(HWND hWnd); //打開并設(shè)置PC串口1(COM1) extern BOOL OpenSerialPort1(); #endif SerialPortControl.cpp文件 #include "StdAfx.h" #include "SerialPortControl.h" HANDLE hCom; //全局變量,串口句柄 HANDLE hCommThread; //全局變量,串口線程 BOOL OpenSerialPort1() { //打開并設(shè)置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; } //以一個(gè)線程不同監(jiān)控串口行接收的數(shù)據(jù) DWORD WINAPI SerialPort1ThreadProcess( HWND hWnd//主窗口句柄) { char str[101]; DWORD wCount; //讀取的字節(jié)數(shù) while(1) { ReadFile(hCom,str, 100, &wCount, NULL); if(wCount > 0) //收到數(shù)據(jù) { str[wCount] = ‘\0‘; ::PostMessage(hWnd, COM_RECVDATA, (unsigned int) str, wCount); //發(fā)送消息給對話框主窗口,以進(jìn)行接收內(nèi)容的顯示 } } return TRUE; } |
![]() |