2013-03-20 64 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