⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 uart_test.cpp

📁 wince下的简单串口测试程序。固定波特率9600
💻 CPP
📖 第 1 页 / 共 2 页
字号:
    return 0;
}
//----------------------------------------------------------------------
// DoMainCommandSendText - Process the Send text button.//
LPARAM DoMainCommandSendText (HWND hWnd, WORD idItem, HWND hwndCtl,
                              WORD wNotifyCode) 
{
     // Set event so that sender thread will send the text.
    SetEvent (g_hSendEvent);
    SetFocus (GetDlgItem (hWnd, ID_SENDTEXT));
    return 0;}

//----------------------------------------------------------------------
// DoMainCommandAbout - Process the Help | About menu command.//
LPARAM DoMainCommandAbout(HWND hWnd, WORD idItem, HWND hwndCtl,
                          WORD wNotifyCode) 
{
    // Use DialogBox to create modal dialog.
    DialogBox (hInst, TEXT ("aboutbox"), hWnd, AboutDlgProc);
    return 0;
}
//======================================================================
// About Dialog procedure//
BOOL CALLBACK AboutDlgProc (HWND hWnd, UINT wMsg, WPARAM wParam,
                            LPARAM lParam) 
{
    switch (wMsg) 
	{
        case WM_COMMAND:
            switch (LOWORD (wParam)) 
			{
                case IDOK:
                case IDCANCEL:
                    EndDialog (hWnd, 0);
                    return TRUE;
		}
        break;
    }
    return FALSE;
}
//----------------------------------------------------------------------
// Helper routine that walks the linkage chain//
INT QueryIrKey (LPTSTR lpszSubkeyName, LPTSTR lpszDevName) 
{
    DWORD dwSize, dwType, dwData;
    HKEY hKey, hSubkey;
    TCHAR szBind[MAX_PATH];
    int rc;
        // Open the IrDA key.
    lstrcpy (szBind, TEXT ("\\Drivers\\BuiltIn\\"));
    lstrcat (szBind, lpszSubkeyName);
    rc = RegOpenKeyEx (HKEY_LOCAL_MACHINE, szBind, 0, 0, &hKey);
  
    if (rc == ERROR_SUCCESS) 
	{
         // Query the device number.
        dwSize = sizeof (dwData);
        rc = RegQueryValueEx (hKey, TEXT ("Port"), 0, &dwType,
                               (PBYTE)&dwData, &dwSize);
        
        	MessageBox(NULL,(TCHAR*)dwData, TEXT("GPSShell"), MB_ICONERROR|MB_TOPMOST);
        if (rc == ERROR_SUCCESS) 
		{

            // Check for valid port number. Assume buffer > 5 chars.
     //       if (dwData < 10)	//stonefu del
                wsprintf (lpszDevName, TEXT ("COM%d:"), dwData);
        } else {
        	MessageBox(NULL,szBind, TEXT("GPSShell"), MB_ICONERROR|MB_TOPMOST);
            // The key doesn't have a port value. Check to see if
             // there is a Parms subkey, and query it.
            lstrcpy (szBind, lpszSubkeyName);
            lstrcat (szBind, TEXT ("\\parms"));
            rc = QueryIrKey (szBind, lpszDevName);
            if (rc)
                return rc;
                        // The key doesn't have a port value or Parms subkey.
             // Check to see if there is a linkage to another reg key.
            rc = RegOpenKeyEx (hKey, TEXT ("linkage"), 0, 0, &hSubkey);
            if (rc == ERROR_SUCCESS) {
                // Yes, get the name of the key to check.
                dwSize = sizeof (szBind);
                rc = RegQueryValueEx (hSubkey, TEXT ("Bind"), 0, &dwType,
                                       (PBYTE)&szBind, &dwSize);
                 // Recurse to examine the linked reg key.
                QueryIrKey (szBind, lpszDevName);
                RegCloseKey (hSubkey);
            }
        }
        RegCloseKey (hKey);
    }
    return lstrlen (lpszDevName);
}
//----------------------------------------------------------------------
// GetRawIrDeviceName - Returns the device name for the RawIR COM port.//
INT GetRawIrDeviceName (LPTSTR lpszDevName) 
{
        *lpszDevName = TEXT ('\0');
    return QueryIrKey (TEXT ("IRDA2413"), lpszDevName);
}
//----------------------------------------------------------------------
// GetIrCommDeviceName - Returns the device name for the IrComm port.//
INT GetIrCommDeviceName (LPTSTR pDevName) 
{
    DWORD dwSize, dwType, dwData;
    HKEY hKey;
     *pDevName = TEXT ('\0');

    // Open the IrDA key.
    if (RegOpenKeyEx (HKEY_LOCAL_MACHINE,
                      TEXT ("Drivers\\BuiltIn\\IrCOMM"), 0,
                      0, &hKey) == ERROR_SUCCESS)
	{
         // Query the device number.
        dwSize = sizeof (dwData);
        if (RegQueryValueEx (hKey, TEXT ("Index"), 0, &dwType,
                             (PBYTE)&dwData, &dwSize) == ERROR_SUCCESS)
             // Check for valid port number. Assume buffer > 5 chars.
            if (dwData < 10)
                wsprintf (pDevName, TEXT ("COM%d:"), dwData);
         RegCloseKey (hKey);
    }
    return lstrlen (pDevName);
}
//----------------------------------------------------------------------
// FillComComboBox - Fills the COM port combo box//
int FillComComboBox (HWND hWnd)
{
    TCHAR szDev[64];
     lstrcpy (szDev, TEXT ("Serial Port   COM1:"));
    SendDlgItemMessage (GetDlgItem (hWnd, IDC_CMDBAR),
                        IDC_COMPORT, CB_INSERTSTRING,
                        -1, (LPARAM)szDev);

     lstrcpy (szDev, TEXT ("Serial Port   COM2:"));
    SendDlgItemMessage (GetDlgItem (hWnd, IDC_CMDBAR),
                        IDC_COMPORT, CB_INSERTSTRING,
                        -1, (LPARAM)szDev);

     lstrcpy (szDev, TEXT ("Serial Port   COM3:"));
     SendDlgItemMessage (GetDlgItem (hWnd, IDC_CMDBAR),
                        IDC_COMPORT, CB_INSERTSTRING,
                        -1, (LPARAM)szDev);
     /*
     lstrcpy (szDev, TEXT ("IrComm Port   "));
    GetIrCommDeviceName (&szDev[lstrlen (szDev)]);
    SendDlgItemMessage (GetDlgItem (hWnd, IDC_CMDBAR),
                        IDC_COMPORT, CB_INSERTSTRING,
                        -1, (LPARAM)szDev);
     lstrcpy (szDev, TEXT ("Raw IR Port   "));
    GetRawIrDeviceName (&szDev[lstrlen (szDev)]);
    SendDlgItemMessage (GetDlgItem (hWnd, IDC_CMDBAR),
                        IDC_COMPORT, CB_INSERTSTRING,
                        -1, (LPARAM)szDev);
    SendDlgItemMessage (GetDlgItem (hWnd, IDC_CMDBAR), IDC_COMPORT,
                        CB_SETCURSEL, 0, 0);
                        */
    return 0;
}
//----------------------------------------------------------------------

// InitCommunication - Open and initialize selected COM port.// 
HANDLE InitCommunication (HWND hWnd, LPTSTR pszDevName) {
    DCB dcb;    INT i;
    TCHAR szDbg[128];
    COMMTIMEOUTS cto;
    HANDLE hLocal;
    DWORD dwTStat;
    hLocal = hComPort;
    hComPort = INVALID_HANDLE_VALUE;
     if (hLocal != INVALID_HANDLE_VALUE)
        CloseHandle (hLocal);  // This causes WaitCommEvent to return.
     // The COM port name is the last 5 characters of the string.
    i = lstrlen (pszDevName);
    hLocal = CreateFile (&pszDevName[i-5], GENERIC_READ | GENERIC_WRITE,
                         0, NULL, OPEN_EXISTING, 0, NULL);
     if (hLocal != INVALID_HANDLE_VALUE)
	 {
        // Configure port.
        GetCommState (hLocal, &dcb);
        dcb.BaudRate = nSpeed;
        dcb.fParity = FALSE;
        dcb.fNull = FALSE;
        dcb.StopBits = ONESTOPBIT;
        dcb.Parity = NOPARITY;
        dcb.ByteSize = 8;
        SetCommState (hLocal, &dcb);
         // Set the timeouts. Set infinite read timeout.
        cto.ReadIntervalTimeout = 0;
        cto.ReadTotalTimeoutMultiplier = 0;
        cto.ReadTotalTimeoutConstant = 0;
        cto.WriteTotalTimeoutMultiplier = 0;
        cto.WriteTotalTimeoutConstant = 0;
        SetCommTimeouts (hLocal, &cto);
        GetCommState (hLocal, &dcb);
        wsprintf (szDbg, TEXT ("Port %s opened\r\n"), pszDevName);
                SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0,
                            (LPARAM)szDbg);
        wsprintf (szDbg, TEXT ("BaudRate=%d \r\n"), dcb.BaudRate);
                SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0,
                            (LPARAM)szDbg);
        wsprintf (szDbg, TEXT ("Parity= %s\r\n"), dcb.Parity);
                SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0,
                            (LPARAM)szDbg);
        wsprintf (szDbg, TEXT ("StopBits= %d \r\n"), dcb.StopBits);
                SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0,
                            (LPARAM)szDbg);
         wsprintf (szDbg, TEXT ("ByteSize= %d \r\n"), dcb.ByteSize);
        	  SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0,
                            (LPARAM)szDbg);
        // Really bad hack to determine which is the raw IR selection.
        // We need to enable IR on the raw IR port in case port is
        // shared with the standard serial port.
        if (*pszDevName == TEXT ('R'))
		{
            if (!EscapeCommFunction (hLocal, SETIR))
			{

                wsprintf (szDbg, TEXT ("Set IR failed. rc %d\r\n"),
                          GetLastError());
                SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL,
                                    0, (LPARAM)szDbg); 
           }
        }
        // Start read thread if not already started.
        hComPort = hLocal;
        if (!GetExitCodeThread (hReadThread, &dwTStat) ||
            (dwTStat != STILL_ACTIVE))
		{
            hReadThread = CreateThread (NULL, 0, ReadThread, hWnd,
                                        0, &dwTStat);
            if (hReadThread)
                CloseHandle (hReadThread);
        }
    } else {
        wsprintf (szDbg, TEXT ("Couldn\'t open port %s. rc=%d\r\n"),
                  pszDevName, GetLastError());
        SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL,
                            0, (LPARAM)szDbg);
    }
    return hComPort;
}
//======================================================================
// SendThread - Sends characters to the serial port//
DWORD WINAPI SendThread(PVOID pArg)
{
    HWND hWnd, hwndSText;
    INT rc;
	DWORD cBytes;
    TCHAR szText[TEXTSIZE],szDbg[TEXTSIZE];
     hWnd = (HWND)pArg;
    hwndSText = GetDlgItem (hWnd, ID_SENDTEXT);
    			wsprintf (szDbg, TEXT ("sendthread start! \r\n"));
        	  SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0,
                            (LPARAM)szDbg);
    while (1)
	{
        rc = WaitForSingleObject (g_hSendEvent, INFINITE);
        if (rc == WAIT_OBJECT_0)
		{
			wsprintf (szDbg, TEXT ("sendthread! \r\n"));
        	  SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0,
                            (LPARAM)szDbg);
            if (!fContinue)
                break;            // Disable send button while sending.
            EnableWindow (GetDlgItem (hWnd, ID_SENDBTN), FALSE);
            GetWindowText (hwndSText, szText, dim(szText));
            lstrcat (szText, TEXT ("\r\n"));
              SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0,
                            (LPARAM)szText);
            rc = WriteFile (hComPort, szText,
				lstrlen (szText)*sizeof(TCHAR),&cBytes, 0);
            if (rc)
			{

                // Copy sent text to output window.
                 SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0,
                                    (LPARAM)TEXT (" >"));
                SetWindowText (hwndSText, TEXT (""));  // Clear text box
            } else
                 // Else, print error message.
                wsprintf (szText, TEXT ("Send failed rc=%d\r\n"),
                           GetLastError());
            // Put text in receive text box.
            SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0,
                                (LPARAM)szText);
            EnableWindow (GetDlgItem (hWnd, ID_SENDBTN), TRUE);
        }
        else
            break;
    	}
    return 0;
}
//======================================================================
// ReadThread - Receives characters from the serial port//
DWORD WINAPI ReadThread(PVOID pArg) 
{
    HWND hWnd;
    INT  i;
	DWORD cBytes;
    TCHAR szText[TEXTSIZE], *pPtr;
    TCHAR szDbg[TEXTSIZE],tch;
     hWnd = (HWND)pArg;

    while (fContinue)
	{
	
        tch = 0;
        pPtr = szText;
        for (i = 0; i < sizeof (szText)-sizeof (TCHAR); i++)
		{
             while (!ReadFile (hComPort, pPtr, 1, &cBytes, 0))
             		if (hComPort == INVALID_HANDLE_VALUE)
                     return 0;             // This syncs the proper byte order for Unicode.
            
            wsprintf (szDbg, TEXT ("%c"),*pPtr);
        	  SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0,
                            (LPARAM)szDbg);
            tch = (tch << 8) & 0xff00;
            tch |= *pPtr++;
            if (tch == TEXT ('\n'))
                break;
        }
	
        /*
        *pPtr++ = 0;  // Avoid alignment problems by addressing as bytes.
        *pPtr++ = 0;         // If out of byte sync, move bytes down one.
        if (i % 2)
		{
            pPtr = szText;

            while (*pPtr || *(pPtr+1))
			{
                *pPtr = *(pPtr+1);
                pPtr++;
            }
            *pPtr = 0;
        }
        */
        SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0,
                            (LPARAM)szText);
    }
    return 0;
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -