2013-03-20 59 views
0

我有一个问题,我想每隔1秒读一次vC++窗体应用程序的串行端口,但是当我调试时,它会在读取串行端口后停止(可以再调试) 。 当我运行它时,程序挂起。在VC++中读取串行端口时挂起

void CENVSConfigDlg::OnTimer(UINT_PTR ID){ 
if(ID==cTimer1){ 

    char Buff[3]="0"; 
    char Buf[6]="0"; 
    int b; 
    int Count = 20; 
    DWORD nbytes; 


    //Read Sensors 

    b=0; //sensor 0 
    sprintf(Buff,"%iz",b); 
    if(!WriteFile(hnd_serial, Buff, Count, &nbytes, NULL)){KillTimer(cTimer1);MessageBox(L"Write Com Port fail!");return;} 

    Sleep(20); 

    if(!ReadFile(hnd_serial, Buf, Count, &nbytes, NULL)){KillTimer(cTimer1);MessageBox(L"Read Com Port fail!");return;} 

    /* Store buf value*/ 
    sensor1 =atoi(Buf); 

    /* Update text box. */ 
    CString string; 
    string.Format(L"%i", sensor1); 
    Sensor_1_edit.SetWindowText((LPCTSTR)string); 
}} 

这里也有相关的代码:

BOOL CENVSConfigDlg::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 



if(!OpenComPort())MessageBox(L"Could not open Adrino port!"); 

return TRUE; // return TRUE unless you set the focus to a control 
} 


    BOOL CENVSConfigDlg::OpenComPort(){ 
//Opens com port to adrino 
DCB conf = { 0 }; 
conf.DCBlength = sizeof(conf); 

if (hnd_serial != INVALID_HANDLE_VALUE) 
    CloseHandle(hnd_serial); 

MessageBox(L"Opening serial connection.\n"); 

hnd_serial = CreateFileA(AdrinoComPort, GENERIC_READ | GENERIC_WRITE, 0, 0, 
         OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); 

if (hnd_serial == INVALID_HANDLE_VALUE) { 
    MessageBox(L"Failed to open serial port.\n"); 
    return FALSE; 
} 

if (!GetCommState(hnd_serial, &conf)) { 
    MessageBox(L"Failed to configure serial port.\n"); 
    CloseHandle(hnd_serial); 
    hnd_serial = INVALID_HANDLE_VALUE; 
    return FALSE; 
} 

conf.BaudRate = CBR_9600; 
conf.ByteSize = 8; 
conf.Parity = NOPARITY; 
conf.StopBits = ONESTOPBIT; 

if (!SetCommState(hnd_serial, &conf)) { 
    MessageBox(L"Failed to configure serial port.\n"); 
    CloseHandle(hnd_serial); 
    hnd_serial = INVALID_HANDLE_VALUE; 
    return FALSE; 
} 
} 

void CENVSConfigDlg::CloseComPort(){ 
//Opens com port to adrino 
if (hnd_serial != INVALID_HANDLE_VALUE) 
    CloseHandle(hnd_serial); 

} 

任何一个可以帮助我,什么是错我的代码

丹尼尔

回答

0

当com端口工作,您通常希望使用comm DCB设置端口的参数。您通常也希望使用SetCommTimeouts来告诉您如何写入以及(尤其是)从通信端口读取数据。

我在previous answer中包含了一个工作示例。

+0

魔法..其工作.. thx很多 – Limavolt 2013-03-20 04:31:25