欢迎来到虫虫下载站 | 资源下载 资源专辑 关于我们
虫虫下载站

ttydlg.cpp

WINCE x86 下串口测试程序源代码。
CPP
字号:
// ttyDlg.cpp : implementation file
//

#include "stdafx.h"
#include "tty.h"
#include "ttyDlg.h"



#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CTtyDlg dialog

CTtyDlg::CTtyDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTtyDlg::IDD, pParent)
{
	m_BaudValue = 9600;      //填充DCB中波特率
	m_ByteSize = 8;          //填充DCB中数据位
	m_Parity = NOPARITY;     //填充DCB中校验位
	m_StopBits = ONESTOPBIT; //填充DCB中停止位
	m_nPort = 0;
	m_nTimer = 0;

	// Communication port name
	hPort = INVALID_HANDLE_VALUE;
	lpszDevName=TEXT("");      

	for(int i = 0; i < BUFSIZE; i++)
		myBuf[i] = 0;
	//{{AFX_DATA_INIT(CTtyDlg)
	m_strTXData = _T("01 02 03 04 05 06 07 08 09");
	m_strRXData = _T("");
	m_dwBaudrate = 5; //9600
	m_dwCheck = 0;    //无校验
	m_bCheckTx = FALSE;
	m_dwDataBit = 2;  //8位
	m_dwPortNum = 0;  //COM1
	m_dwStopBit = 0;  //1
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32

	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CTtyDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTtyDlg)
	DDX_Text(pDX, IDC_EDITTXD, m_strTXData);
	DDX_Text(pDX, IDC_RXDBUF, m_strRXData);
	DDX_CBIndex(pDX, IDC_BAUD, m_dwBaudrate);
	DDX_CBIndex(pDX, IDC_CHECK, m_dwCheck);
	DDX_Check(pDX, IDC_CHECKSEND, m_bCheckTx);
	DDX_CBIndex(pDX, IDC_DATABIT, m_dwDataBit);
	DDX_CBIndex(pDX, IDC_PORTNUM, m_dwPortNum);
	DDX_CBIndex(pDX, IDC_STOPBIT, m_dwStopBit);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTtyDlg, CDialog)
	//{{AFX_MSG_MAP(CTtyDlg)
	ON_WM_HELPINFO()
	ON_BN_CLICKED(IDC_MANUALSEND, OnManualsend)
	ON_BN_CLICKED(IDC_OPENCOM, OnOpencom)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_CLOSECOM, OnClosecom)
    ON_MESSAGE(WM_COMMNOTIFY, OnComNotify)
	ON_BN_CLICKED(IDC_RADIORXD, OnRadiorxd)
	ON_BN_CLICKED(IDC_RADIOSEND, OnRadiosend)
	ON_WM_TIMER()
	ON_WM_CANCELMODE()
	ON_WM_CAPTURECHANGED()
	ON_WM_CLOSE()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTtyDlg message handlers

BOOL CTtyDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// 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
	
	CenterWindow(GetDesktopWindow());	// center to the hpc screen

	//disable IDC_CLOSECOM button
	CButton *pButton;
	pButton =(CButton*)GetDlgItem(IDC_CLOSECOM);
	pButton->EnableWindow(FALSE);
	pButton = NULL;
	
	//enable IDC_OPENCOM button
	pButton =(CButton*)GetDlgItem(IDC_OPENCOM);
	pButton->EnableWindow(TRUE);
	pButton = NULL;

    // TODO: Add extra initialization here
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CTtyDlg::OnHelpInfo()
{
	// TODO: implement help here
	MessageBox(_T("Help"));
}

HCURSOR CTtyDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CTtyDlg::OnManualsend() 
{
	BOOL bSuccess;

	UpdateData(TRUE); //读取编辑框内容
	bSuccess = AnaFunc(m_strTXData); //analysis data, and then tx it.

	if(!bSuccess)
		AfxMessageBox(TEXT("Can't TX data successful!"));

	return ;
}

void CTtyDlg::OnOpencom() 
{

	TCHAR  Buf[20];

	hPort = INVALID_HANDLE_VALUE;            // Serial port handle
	UpdateData(TRUE); //retrieve the dialog data

	//disable IDC_OPENCOM button
	CButton *pButton;
	pButton =(CButton*)GetDlgItem(IDC_OPENCOM);
	pButton->EnableWindow(FALSE);
	pButton = NULL;
	
	//enable IDC_OPENCOM button
	pButton =(CButton*)GetDlgItem(IDC_CLOSECOM);
	pButton->EnableWindow(TRUE);
	pButton = NULL;
	
	InitCommPara();
    swprintf(Buf,TEXT("COM%d:"),m_nPort);
	
	lpszDevName = Buf; //Preserve the content of Buf
	 //  lpszDevName = TEXT(Buf);
   	// Initialize the port.
	if (!PortInitialize (Buf,m_BaudValue\
		,m_ByteSize,m_Parity,m_StopBits))
	{
		return ;
	}
	m_nTimer = SetTimer(1,500,0); //start the timer
//	printf("Serial Port has already open\n\n") ;
	return; 
}

void CTtyDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

//		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}


void CTtyDlg::InitCommPara()
{
	GetSerialPort(); //get the serialport no.
	GetBaud();       //get the baudrate of port
	GetByteSize();   //get the bytesize of port
	GetParity();     //get the parity of port
	GetStopBit();    //get the stopbit of port
}

void CTtyDlg::GetBaud(void)
{
	switch(m_dwBaudrate)
	{
	case 0: m_BaudValue = 300; break;
	case 1: m_BaudValue = 600; break;
	case 2: m_BaudValue = 1200;break;
	case 3: m_BaudValue = 2400;break;
	case 4: m_BaudValue = 4800;break;
	case 5: m_BaudValue = 9600;break;
	case 6: m_BaudValue =19200;break;
	case 7: m_BaudValue =38400;break;
	case 8: m_BaudValue =57600;break;
	default: m_BaudValue = 9600;break;
	}
}

void CTtyDlg::GetByteSize(void)
{
	switch(m_dwDataBit)
	{
	case 0: m_ByteSize=6;break;
	case 1: m_ByteSize=7;break;
	case 2: m_ByteSize=8;break;
	default: m_ByteSize=8; break;
	}
}

void CTtyDlg::GetParity(void)
{
	switch(m_dwCheck)
	{
	case 0: m_Parity=NOPARITY;break;
	case 1: m_Parity=ODDPARITY;break;
	case 2: m_Parity=EVENPARITY;break;
	default: m_Parity=NOPARITY;break;
	}
}

void CTtyDlg::GetStopBit(void)
{
	switch(m_dwStopBit)
	{
	case 0:  m_StopBits=ONESTOPBIT;break;
	case 1:  m_StopBits=TWOSTOPBITS;break;
	default: m_StopBits=ONESTOPBIT;break;
	}
}

void CTtyDlg::GetSerialPort()
{
	switch(m_dwPortNum)
	{
	case 0: m_nPort=1;break;
	case 1: m_nPort=2;break;
	case 2: m_nPort=3;break;
	case 3: m_nPort=4;break;
	case 4: m_nPort=5;break;
	default: m_nPort=1;break;
	}
}

void CTtyDlg::OnClosecom() 
{
	//disable IDC_CLOSECOM button
	CButton *pButton;
	pButton =(CButton*)GetDlgItem(IDC_CLOSECOM);
	pButton->EnableWindow(FALSE);
	pButton = NULL;
	
	//enable IDC_OPENCOM button
	pButton =(CButton*)GetDlgItem(IDC_OPENCOM);
	pButton->EnableWindow(TRUE);
	pButton = NULL;

	if (PortClose(hPort))
	{
		::MessageBox (NULL, TEXT("Comm Port already Closed"), 
                TEXT("Error"), MB_OK);
	}

	CloseHandle( hPort ) ;
	hPort = NULL;

	KillTimer(m_nTimer);  
}

void CTtyDlg::OnComNotify(WPARAM wParam, LPARAM lParam)
{
	BYTE nLen; //receive the length of data
	BYTE *pBuf = NULL;
	CString str = _T("");

	nLen = (BYTE)wParam;   //data length
    pBuf = (BYTE *)lParam; //data buffer

	ASSERT(nLen > 0);
	ASSERT(pBuf != NULL); //EXCEPTION

	UpdateData(TRUE); //retrieve data from dialog

	CEdit *pEdit = NULL;
	pEdit = (CEdit *)GetDlgItem(IDC_RXDBUF);
	pEdit->GetWindowText(m_strRXData);

	for(int i =0; i < nLen;i++)	{
		str.Format(_T("%d"),pBuf[i]);
		m_strRXData += _T(" ")+str+_T(" ");
	}
	pEdit->SetWindowText(m_strRXData);
	UpdateData(FALSE);
	
}

void CTtyDlg::OnRadiorxd() 
{
	m_strRXData = _T("");		
	UpdateData(FALSE);
}

void CTtyDlg::OnRadiosend() 
{
	m_strTXData = _T("");
	UpdateData(FALSE);
}

void CTtyDlg::OnTimer(UINT nIDEvent) 
{
	if(m_nPort == 0)
		return;
    CommWatchProc(); //interrogate serial port data 
	CDialog::OnTimer(nIDEvent);
}

void CTtyDlg::OnCancelMode() 
{
	CDialog::OnCancelMode();
	
	// TODO: Add your message handler code here
}

BOOL CTtyDlg::AnaFunc(CString str)
{
	BYTE buf[100];
	WORD DataLen=0;
	    
	memset(buf,0,100);
	str.TrimLeft();
	DataLen = str.GetLength();

	if(DataLen==0 || str == _T(""))
		return FALSE;

	LPTSTR p = str.GetBuffer(DataLen+1);
	DataLen = (DataLen+1)/3; //calculate the data length of buffer


	for(int i=0;i<DataLen;i++,p+=3) //analysz data from buffer
	{
		BYTE nValue,nValue1,nValue2;

		for(int j=0;j<2;j++)
			(p[j] > 0x40)?(p[j] -= 0X37):(p[j] -= 0X30);
		nValue1=p[0];
		nValue2=p[1];
		nValue = p[0]*16+p[1];
		buf[i] = nValue;
	}

	str.ReleaseBuffer();

	for(i=0;i<DataLen;i++)
		PortWrite(buf[i]);//tx data 
	 return TRUE;
}

void CTtyDlg::OnCaptureChanged(CWnd *pWnd) 
{
	// TODO: Add your message handler code here
	
	CDialog::OnCaptureChanged(pWnd);
}

void CTtyDlg::OnClose() 
{
	// TODO: Add your message handler code here and/or call default
	CDialog::OnClose();
}


/*******************************************************
function:
	CommWatchProc
	监视串口数据
********************************************************/
UINT CTtyDlg::CommWatchProc(void)
{
   DWORD dwLen=0;
   BOOL       fReadStat ;
//   COMSTAT    ComStat ;
//   DWORD      dwErrorFlags;
   CString str = _T("");
   BYTE buf[256];
   
   memset(buf,0,256);

   dwLen = 100;

//   ClearCommError(hPort, &dwErrorFlags, &ComStat);
//   dwLen = min(255,ComStat.cbInQue);

//   if(dwLen > 0)
//   {
		fReadStat = ReadFile(hPort, buf, dwLen, &dwLen, 0) ;
		if(!fReadStat)
				return 0;

		UpdateData(TRUE); //retrieve data from dialog

	    CEdit *pEdit = NULL;
	    pEdit = (CEdit *)GetDlgItem(IDC_RXDBUF);
	    pEdit->GetWindowText(m_strRXData);

	    for(int i =0; i<dwLen;i++)
		{
		   str.Format(_T("%2x"),buf[i]);
		   m_strRXData += _T(" ")+str+_T(" ");
		   str = _T("");
		}
	    pEdit->SetWindowText(m_strRXData);
	    UpdateData(FALSE);
//   }
   return(dwLen);
} 



/***********************************************************************

  PortInitialize (LPTSTR lpszPortName)

***********************************************************************/
BOOL CTtyDlg::PortInitialize (LPTSTR lpszPortName\
					 ,DWORD dwBaudrate \
					 ,BYTE  ByteSize \
					 ,BYTE  Parity   \
					 ,BYTE  StopBits
					 )
{
  DWORD dwError;
  DCB PortDCB;					// Port Control Settings Structure
  COMMTIMEOUTS CommTimeouts;	// Comm port timeout structure

  // Open the serial port.
  hPort = CreateFile (lpszPortName, // Pointer to the name of the port
                      GENERIC_READ | GENERIC_WRITE,
                                    // Access (read-write) mode
                      0,            // Share mode
                      NULL,         // Pointer to the security attribute
                      OPEN_EXISTING,// How to open the serial port
                      0,            // Port attributes
                      NULL);        // Handle to port with attribute
                                    // to copy

  // If it fails to open the port, return FALSE.
  if ( hPort == INVALID_HANDLE_VALUE ) 
  {
    // Could not open the port.
    dwError = GetLastError ();
    return FALSE;
  }

  PortDCB.DCBlength = sizeof (DCB);     

  // Get the default port setting information.
  GetCommState (hPort, &PortDCB);

  // Change the DCB structure settings.
  PortDCB.BaudRate = dwBaudrate;              // Current baud 
  PortDCB.fBinary = TRUE;               // Binary mode; no EOF check 
  PortDCB.fParity = TRUE;               // Enable parity checking 
  PortDCB.fOutxCtsFlow = FALSE;         // No CTS output flow control 
  PortDCB.fOutxDsrFlow = FALSE;         // No DSR output flow control 
  PortDCB.fDtrControl = DTR_CONTROL_ENABLE; 
                                        // DTR flow control type 
  PortDCB.fDsrSensitivity = FALSE;      // DSR sensitivity 
  PortDCB.fTXContinueOnXoff = TRUE;     // XOFF continues Tx 
  PortDCB.fOutX = FALSE;                // No XON/XOFF out flow control 
  PortDCB.fInX = FALSE;                 // No XON/XOFF in flow control 
  PortDCB.fErrorChar = FALSE;           // Disable error replacement 
  PortDCB.fNull = FALSE;                // Disable null stripping 
  PortDCB.fRtsControl = RTS_CONTROL_ENABLE; 
                                        // RTS flow control 
  PortDCB.fAbortOnError = FALSE;        // Do not abort reads/writes on 
                                        // error
  PortDCB.ByteSize = ByteSize;                 // Number of bits/byte, 4-8 
  PortDCB.Parity = Parity;            // 0-4=no,odd,even,mark,space 
  PortDCB.StopBits = StopBits;        // 0,1,2 = 1, 1.5, 2 

  // Configure the port according to the specifications of the DCB 
  // structure.
  if (!SetCommState (hPort, &PortDCB))
  {
    // Could not create the read thread.
    dwError = GetLastError ();
    return FALSE;
  }

  // Retrieve the time-out parameters for all read and write operations
  // on the port. 
  GetCommTimeouts (hPort, &CommTimeouts);

  // Change the COMMTIMEOUTS structure settings.
  CommTimeouts.ReadIntervalTimeout = MAXDWORD;  
  CommTimeouts.ReadTotalTimeoutMultiplier = 0;  
  CommTimeouts.ReadTotalTimeoutConstant = 0;    
  CommTimeouts.WriteTotalTimeoutMultiplier = 10;  
  CommTimeouts.WriteTotalTimeoutConstant = 1000;    

  // Set the time-out parameters for all read and write operations
  // on the port. 
  if (!SetCommTimeouts (hPort, &CommTimeouts))
  {
    // Could not create the read thread.
    dwError = GetLastError ();
    return FALSE;
  }

  // Direct the port to perform extended functions SETDTR and SETRTS
  // SETDTR: Sends the DTR (data-terminal-ready) signal.
  // SETRTS: Sends the RTS (request-to-send) signal. 
  EscapeCommFunction (hPort, SETDTR);
  EscapeCommFunction (hPort, SETRTS);

  return TRUE;
}


/***********************************************************************

  PortClose (HANDLE hCommPort)

***********************************************************************/
BOOL CTtyDlg::PortClose (HANDLE hCommPort)
{
  DWORD dwError;

  if (hCommPort != INVALID_HANDLE_VALUE)
  {
    // Close the communication port.
    if (!CloseHandle (hCommPort))
    {
      dwError = GetLastError ();
      return FALSE;
    }
    else
    {
      hCommPort = INVALID_HANDLE_VALUE;
      return TRUE;
    }
  }

  return FALSE;
}

/***********************************************************************

  PortWrite (BYTE Byte)

***********************************************************************/
void CTtyDlg::PortWrite (BYTE Byte)
{
  DWORD dwError=0;
  DWORD dwNumBytesWritten=0;

  if (!WriteFile (hPort,              // Port handle
                  &Byte,              // Pointer to the data to write 
                  1,                  // Number of bytes to write
                  &dwNumBytesWritten, // Pointer to the number of bytes 
                                      // written
                  NULL))              // Must be NULL for Windows CE
  {
    // WriteFile failed. Report error.
    dwError = GetLastError ();
  }
}




⌨️ 快捷键说明

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