PC串口通信源码

  1. // commDlg.cpp : implementation file   
  2. //   
  3.    
  4. #include "stdafx.h"   
  5. #include "comm.h"   
  6. #include "commDlg.h"   
  7.    
  8. #ifdef _DEBUG   
  9. #define new DEBUG_NEW   
  10. #undef THIS_FILE   
  11. static char THIS_FILE[] = __FILE__;   
  12. #endif   
  13.    
  14. /////////////////////////////////////////////////////////////////////////////   
  15. // CAboutDlg dialog used for App About   
  16.    
  17. class CAboutDlg : public CDialog   
  18. {   
  19. public:   
  20.     CAboutDlg();   
  21.        
  22.     // Dialog Data   
  23.     //{{AFX_DATA(CAboutDlg)   
  24.     enum { IDD = IDD_ABOUTBOX };   
  25.     //}}AFX_DATA   
  26.        
  27.     // ClassWizard generated virtual function overrides   
  28.     //{{AFX_VIRTUAL(CAboutDlg)   
  29. protected:   
  30.     virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support   
  31.     //}}AFX_VIRTUAL   
  32.        
  33.     // Implementation   
  34. protected:   
  35.     //{{AFX_MSG(CAboutDlg)   
  36.     //}}AFX_MSG   
  37.     DECLARE_MESSAGE_MAP()   
  38. };   
  39.    
  40. CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)   
  41. {   
  42.     //{{AFX_DATA_INIT(CAboutDlg)   
  43.     //}}AFX_DATA_INIT   
  44. }   
  45.    
  46. void CAboutDlg::DoDataExchange(CDataExchange* pDX)   
  47. {   
  48.     CDialog::DoDataExchange(pDX);   
  49.     //{{AFX_DATA_MAP(CAboutDlg)   
  50.     //}}AFX_DATA_MAP   
  51. }   
  52.    
  53. BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)   
  54. //{{AFX_MSG_MAP(CAboutDlg)   
  55. // No message handlers   
  56. //}}AFX_MSG_MAP   
  57. END_MESSAGE_MAP()   
  58.    
  59. /////////////////////////////////////////////////////////////////////////////   
  60. // CCommDlg dialog   
  61.    
  62. CCommDlg::CCommDlg(CWnd* pParent /*=NULL*/)   
  63. : CDialog(CCommDlg::IDD, pParent)   
  64. {   
  65.     //{{AFX_DATA_INIT(CCommDlg)   
  66.     m_SendData = _T("");   
  67.     m_ReceiveData = _T("");   
  68.     //}}AFX_DATA_INIT   
  69.     // Note that LoadIcon does not require a subsequent DestroyIcon in Win32   
  70.     stop=FALSE;   
  71.     m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);   
  72. }   
  73.    
  74. void CCommDlg::DoDataExchange(CDataExchange* pDX)   
  75. {   
  76.     CDialog::DoDataExchange(pDX);   
  77.     //{{AFX_DATA_MAP(CCommDlg)   
  78.     DDX_Control(pDX, IDC_STOPRECV, m_stop);   
  79.     DDX_Control(pDX, IDC_HEXSEND, m_hexsend);   
  80.     DDX_Control(pDX, IDC_COMSEEPED, m_speed);   
  81.     DDX_Control(pDX, IDC_HEX, m_hex);   
  82.     DDX_Control(pDX, IDC_COMSELECT, m_com);   
  83.     DDX_Control(pDX, IDC_MSCOMM1, m_Comm);   
  84.     DDX_Text(pDX, IDC_EDIT1, m_SendData);   
  85.     DDX_Text(pDX, IDC_EDIT2, m_ReceiveData);   
  86.     //}}AFX_DATA_MAP   
  87. }   
  88.    
  89. BEGIN_MESSAGE_MAP(CCommDlg, CDialog)   
  90. //{{AFX_MSG_MAP(CCommDlg)   
  91. ON_WM_SYSCOMMAND()   
  92. ON_WM_PAINT()   
  93. ON_WM_QUERYDRAGICON()   
  94. ON_BN_CLICKED(IDC_BUTTON1, OnButton1)   
  95. ON_BN_CLICKED(IDC_BUTTON2, OnButton2)   
  96. ON_CBN_SELENDOK(IDC_COMSELECT, OnComselect)   
  97. ON_CBN_SELENDOK(IDC_COMSEEPED, OnComspeed)   
  98. ON_BN_CLICKED(IDC_STOPRECV, OnStoprecv)   
  99. //}}AFX_MSG_MAP   
  100. END_MESSAGE_MAP()   
  101.    
  102. /////////////////////////////////////////////////////////////////////////////   
  103. // CCommDlg message handlers   
  104.    
  105. BOOL CCommDlg::OnInitDialog()   
  106. {   
  107.     CDialog::OnInitDialog();   
  108.        
  109.     // Add "About..." menu item to system menu.   
  110.        
  111.     // IDM_ABOUTBOX must be in the system command range.   
  112.     ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);   
  113.     ASSERT(IDM_ABOUTBOX < 0xF000);   
  114.        
  115.     CMenu* pSysMenu = GetSystemMenu(FALSE);   
  116.     if (pSysMenu != NULL)   
  117.     {   
  118.         CString strAboutMenu;   
  119.         strAboutMenu.LoadString(IDS_ABOUTBOX);   
  120.         if (!strAboutMenu.IsEmpty())   
  121.         {   
  122.             pSysMenu->AppendMenu(MF_SEPARATOR);   
  123.             pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);   
  124.         }   
  125.     }   
  126.        
  127.     // Set the icon for this dialog.  The framework does this automatically   
  128.     //  when the application's main window is not a dialog   
  129.     SetIcon(m_hIcon, TRUE);         // Set big icon   
  130.     SetIcon(m_hIcon, FALSE);        // Set small icon   
  131.        
  132.     // TODO: Add extra initialization here   
  133.     m_com.SetCurSel(0);   
  134.     m_speed.SetCurSel(2);   
  135.     return TRUE;  // return TRUE  unless you set the focus to a control   
  136. }   
  137.    
  138. void CCommDlg::OnSysCommand(UINT nID, LPARAM lParam)   
  139. {   
  140.     if ((nID & 0xFFF0) == IDM_ABOUTBOX)   
  141.     {   
  142.         CAboutDlg dlgAbout;   
  143.         dlgAbout.DoModal();   
  144.     }   
  145.     else   
  146.     {   
  147.         CDialog::OnSysCommand(nID, lParam);   
  148.     }   
  149. }   
  150.    
  151. // If you add a minimize button to your dialog, you will need the code below   
  152. //  to draw the icon.  For MFC applications using the document/view model,   
  153. //  this is automatically done for you by the framework.   
  154.    
  155. void CCommDlg::OnPaint()    
  156. {   
  157.     if (IsIconic())   
  158.     {   
  159.         CPaintDC dc(this); // device context for painting   
  160.            
  161.         SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);   
  162.            
  163.         // Center icon in client rectangle   
  164.         int cxIcon = GetSystemMetrics(SM_CXICON);   
  165.         int cyIcon = GetSystemMetrics(SM_CYICON);   
  166.         CRect rect;   
  167.         GetClientRect(&rect);   
  168.         int x = (rect.Width() - cxIcon + 1) / 2;   
  169.         int y = (rect.Height() - cyIcon + 1) / 2;   
  170.            
  171.         // Draw the icon   
  172.         dc.DrawIcon(x, y, m_hIcon);   
  173.     }   
  174.     else   
  175.     {   
  176.         CDialog::OnPaint();   
  177.     }   
  178. }   
  179.    
  180. // The system calls this to obtain the cursor to display while the user drags   
  181. //  the minimized window.   
  182. HCURSOR CCommDlg::OnQueryDragIcon()   
  183. {   
  184.     return (HCURSOR) m_hIcon;   
  185. }   
  186.    
  187. BEGIN_EVENTSINK_MAP(CCommDlg, CDialog)   
  188. //{{AFX_EVENTSINK_MAP(CCommDlg)   
  189. ON_EVENT(CCommDlg, IDC_MSCOMM1, 1 /* OnComm */, OnComm, VTS_NONE)   
  190. //}}AFX_EVENTSINK_MAP   
  191. END_EVENTSINK_MAP()   
  192.    
  193. //------------------------------------------------------------------------------------------   
  194. void CCommDlg::OnComm()    
  195. {   
  196.     //-------------------------   
  197.     //   判断是否停止接收   
  198.     //-------------------------   
  199.     if(stop)   
  200.     {   
  201.         return;   
  202.     }   
  203.    
  204.     //-------------------------   
  205.     //       变量定义   
  206.     //-------------------------   
  207. //  VARIANT m_input1;   
  208.     COleSafeArray m_input2;   
  209.     long length,i;   
  210.     BYTE data[1024];                             //一般设置为BYTE类型   
  211.     CString str;   
  212.        
  213.     if(m_Comm.GetCommEvent()==2)                 //接收缓冲区内有字符   
  214.     {   
  215. //      m_input1=m_Comm.GetInput();              //读取缓冲区内的数据   
  216. //      m_input2=m_input1;                       //将VARIANT型变量转换为ColeSafeArray型变量   
  217.    
  218.         m_input2.Attach(m_Comm.GetInput());      //确保使用时内存不会一直增大,自己修改   
  219.         length=m_input2.GetOneDimSize();         //确定数据长度   
  220.    
  221.         for(i=0;i<length;i++)   
  222.             m_input2.GetElement(&i,data+i);      //将数据转换为BYTE型数组   
  223.            
  224.         for(i=0;i<length;i++)                    //将数组转换为Cstring型变量   
  225.         {   
  226.             BYTE a=* (char *)(data+i);   
  227.    
  228.             if(m_hex.GetCheck())   
  229.             {   
  230.                 str.Format("%02X ",a);           //将字符转换成16进制来存储   
  231.             }   
  232.             else    
  233.             {   
  234.                 str.Format("%c",a);   
  235.             }   
  236.    
  237.             m_ReceiveData+=str;   
  238.         }   
  239.     }   
  240.        
  241.     UpdateData(FALSE);                           //更新编辑框内容   
  242. }   
  243.    
  244. //-------------------------------------------------------------------------------------------   
  245.    
  246. char HexChar(char c)           //检测一个字符是不是十六进制字符,若是返回相应的值,否则返回0x10;   
  247. {      
  248.     if((c>='0')&&(c<='9'))   
  249.     {   
  250.         return c-0x30;   
  251.     }   
  252.    
  253.     else if((c>='A')&&(c<='F'))   
  254.     {   
  255.         return c-'A'+10;   
  256.     }   
  257.    
  258.     else if((c>='a')&&(c<='f'))   
  259.     {   
  260.         return c-'a'+10;   
  261.     }   
  262.    
  263.     else return 0x10;   
  264. }   
  265.    
  266. //------------------------------------------------------------------------------   
  267.    
  268. int Str2Hex(CString str,CByteArray &data)   
  269. {   
  270.     //-----------------------------------------------------------------------   
  271.     //   将一个字符串作为十六进制串转化为一个字节数组,字节间可用空格分隔,   
  272.     //   返回转换后的字节数组长度,同时字节数组长度自动设置。   
  273.     //-----------------------------------------------------------------------   
  274.        
  275.     int t,t1;                         //每个字节存储两位,比如 "AB" ,转换为16进制以后就成了 0xAB   
  276.     int rlen=0,len=str.GetLength();   
  277.        
  278.     data.SetSize(len/2);   
  279.    
  280.     for(int i=0;i<len;)   
  281.     {   
  282.         char l,h=str[i];   
  283.         if(h==' ')   
  284.         {   
  285.             i++;   
  286.             continue;   
  287.         }   
  288.    
  289.         i++;   
  290.         if(i>=len)   
  291.             break;   
  292.    
  293.         l=str[i];   
  294.    
  295.         t=HexChar(h);   
  296.         t1=HexChar(l);   
  297.    
  298.         if((t==16)||(t1==16))   
  299.             break;   
  300.         else    
  301.         {   
  302.             t=t*16+t1;   
  303.         }   
  304.    
  305.         i++;   
  306.         data[rlen]=(char)t;   
  307.         rlen++;   
  308.     }   
  309.    
  310.     data.SetSize(rlen);   
  311.    
  312.     return rlen;   
  313. }   
  314.    
  315. //--------------------------------------------------------------------------------------   
  316. void CCommDlg::OnButton1()    
  317. {   
  318.     //-----------------------------   
  319.     //     检查串口是否已打开   
  320.     //-----------------------------   
  321.     if( !m_Comm.GetPortOpen())   
  322.         m_Comm.SetPortOpen(TRUE);                   //打开串口   
  323.        
  324.     UpdateData(TRUE);   
  325.    
  326.     m_SendData += "\r\n";   
  327.     if(m_hexsend.GetCheck())   
  328.     {   
  329.         CByteArray data;   
  330.    
  331.         int len=Str2Hex(m_SendData,data);   
  332.         m_Comm.SetOutput(COleVariant(data));        //发送数据   
  333.     }   
  334.     else    
  335.         m_Comm.SetOutput(COleVariant(m_SendData));  //发送数据   
  336.        
  337. }   
  338.    
  339. //--------------------------------------------------------------------------------------   
  340. void CCommDlg::OnButton2()    
  341. {   
  342.     m_ReceiveData.Empty();//清除接收对话框中的数据   
  343.        
  344.     //m_SendData.Empty();//清除发送对话框中的数据   
  345.        
  346.     UpdateData(FALSE);    //这里的实现不是很好,容易将以前的数据还原在发送框   
  347.    
  348. //  COleSafeArray  SAFEARRAY;   
  349.        
  350. }   
  351.    
  352. //--------------------------------------------------------------------------------------   
  353. void CCommDlg::OnComselect()    
  354. {   
  355.     if(m_Comm.GetPortOpen())   
  356.         m_Comm.SetPortOpen(FALSE);   
  357.        
  358.     m_Comm.SetCommPort(m_com.GetCurSel()+1);   
  359.        
  360. }   
  361.    
  362. //--------------------------------------------------------------------------------------   
  363. void CCommDlg::OnComspeed()    
  364. {   
  365.     CString temp;   
  366.    
  367.     int i=m_speed.GetCurSel();   
  368.    
  369.     switch(i)   
  370.     {   
  371.     case 0:   
  372.         i=2400;   
  373.         break;   
  374.     case 1:   
  375.         i=4800;   
  376.         break;   
  377.     case 2:   
  378.         i=9600;   
  379.         break;   
  380.     case 3:   
  381.         i=19200;   
  382.         break;   
  383.     case 4:   
  384.         i=38400;   
  385.         break;   
  386.     case 5:   
  387.         i=115200;   
  388.         break;   
  389.     }   
  390.    
  391.     temp.Format("%d,n,8,1",i);   
  392.     m_Comm.SetSettings(temp);   
  393. }   
  394.    
  395. //---------------------------------------------------------------------------------------   
  396. void CCommDlg::OnStoprecv()    
  397. {   
  398.     stop=!stop;   
  399.     if(stop)   
  400.         m_stop.SetWindowText("继续接收");   
  401.     else   
  402.         m_stop.SetWindowText("停止接收");   
  403. }   
  404.    
  405. //---------------------------------------------------------------------------------------   
  406. BOOL CCommDlg::PreTranslateMessage(MSG* pMsg)    
  407. {   
  408.     // TODO: Add your specialized code here and/or call the base class   
  409.    
  410.     if(pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_RETURN)   
  411.     {   
  412.         return TRUE;   
  413.     }   
  414.        
  415.     return CDialog::PreTranslateMessage(pMsg);   
  416. }   


posted @ 2013-08-19 18:58  Jremmy  阅读(348)  评论(0)    收藏  举报