一些应用范例 :
当然首先 #include "com_class.h"
一、打开串口1同步写
char str[] = "com_class test"; _sync_com com1; //同步 com1.open(1); // 相当于 com1.open(1, 9600); com1.open(1, "9600,8,n,1"); for(int i=0; i<100; i++) { Sleep(500); com1.write(str); //也可以 com1.write(str, strlen(str)); } com1.close(); |
二、打开串口2异步读
char str[100]; _asyn_com com2; //异步 com2.open(2); // 相当于 com2.open(2, 9600); com2.open(2, "9600,8,n,1"); if(!com2.is_open()) cout << "COM2 not open , error : " << GetLastError() << endl; /* 也可以如下用法 if(!com2.open(2)) cout << "COM2 not open , error : " << GetLastError() << endl; */ for(int i=0; i<100; i++) { Sleep(500); if(com2.read(str, 100) > 0)//异步读,返回读取字符数 cout << str; } com2.close(); |
三、扩展应用具有监视线程的串口类
class _com_ex : public thread_com { public: virtual on_receive() { char str[100]; if(read(str, 100) > 0)//异步读,返回读取字符数 cout << str; } }; int main(int argc, char *argv[]) { try { char str[100]; _com_ex com2; //异步扩展 com2.open(2); Sleep(10000); com2.close(); } catch(exception &e) { cout << e.what() << endl; } return 0; } |
四、桌面应用可发送消息到指定窗口(在C++ Builder 和 VC ++ 测试通过)
VC ++ 接受消息
BEGIN_MESSAGE_MAP(ComDlg, CDialog) //{{AFX_MSG_MAP(ComDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_DESTROY() //}}AFX_MSG_MAP ON_MESSAGE(ON_COM_RECEIVE, On_Receive) END_MESSAGE_MAP() |
打开串口,传递窗口句柄
_thread_com com2; com2.open(2); com2.set_hwnd(ComDlg->m_hWnd); |
处理消息
LRESULT ComDlg::On_Receive(WPARAM wp, LPARAM lp) { char str[100]; com2.read(str, 100); char com_str[10]; strcpy(com_str, "COM"); ltoa((long)wp, com_str + 3, 10); // WPARAM 保存端口号 MessageBox(str, com_str, MB_OK); return 0; } |
C++ Builder
class TForm1 : public TForm { __published: // IDE-managed Components void __fastcall FormClose(TObject *Sender, TCloseAction &Action); void __fastcall FormCreate(TObject *Sender); private: // User declarations public: // User declarations void On_Receive(TMessage& Message); __fastcall TForm1(TComponent* Owner); _thread_com com2; BEGIN_MESSAGE_MAP MESSAGE_HANDLER(ON_COM_RECEIVE, TMessage, On_Receive) END_MESSAGE_MAP(TForm) }; void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action) { com2.close(); } //--------------------------------------------------------------------------- void __fastcall TForm1::FormCreate(TObject *Sender) { com2.open(2); com2.set_hwnd(Handle); } //--------------------------------------------------------------------------- void TForm1::On_Receive(TMessage& Message) { char xx[20]; int port = Message.WParam; if(com2.read(xx, 20) > 0) ShowMessage(xx); } |